class Timer
Timer
handler, manage multiple Action
objects, calling them when required. When the Timer
is constructed, a new Thread is created to manage timed delays and run Actions.
XXX: there is no way to stop the timer currently. I’m keeping it this way to weed out old Timer
implementation legacy in rbot code. -jsn.
Public Class Methods
Public Instance Methods
Source
# File lib/rbot/timer.rb, line 138 def add(period, opts = {}, &block) a = Action.new({:repeat => true, :period => period}.merge(opts), &block) self.synchronize do @actions[a.object_id] = a @tick.signal end return a.object_id end
Creates and installs a new Action
, repeatable by default.
Returns the id of the created Action
Source
Source
Source
# File lib/rbot/timer.rb, line 188 def configure(aid, opts = {}, &block) self.synchronize do self[aid].configure(opts, &block) @tick.signal end end
Provides for on-the-fly reconfiguration of Actions
Source
# File lib/rbot/timer.rb, line 176 def remove(aid) self.synchronize do @actions.delete(aid) # or raise "nonexistent action #{aid}" end end
removes an existing blocked Action
Also aliased as: delete
Source
Source
# File lib/rbot/timer.rb, line 203 def start raise 'already started' if @thread @stopping = false debug "starting timer #{self}" @thread = Thread.new do loop do tmout = self.run_actions break if tmout and tmout < 0 self.synchronize { @tick.wait(tmout) } end end end
Source
# File lib/rbot/timer.rb, line 216 def stop raise 'already stopped' unless @thread debug "stopping timer #{self}..." @stopping = true self.synchronize { @tick.signal } @thread.join(60) or @thread.kill debug "timer #{self} stopped" @thread = nil end
Source
Protected Instance Methods
Source
# File lib/rbot/timer.rb, line 228 def [](aid) aid ||= @current raise "no current action" unless aid raise "nonexistent action #{aid}" unless @actions.include? aid @actions[aid] end
Source
# File lib/rbot/timer.rb, line 235 def run_actions(now = Time.now) @actions.keys.each do |k| return -1 if @stopping a = @actions[k] or next next if a.blocked? || a.next > now begin @current = k a.run(now) ensure @current = nil end @actions.delete k unless a.next end nxt = @actions.values.find_all { |v| !v.blocked? }.map{ |v| v.next }.min if nxt delta = nxt - now delta = 0 if delta < 0 return delta else return nil end end