| Class | Timer::Action |
| In: |
lib/rbot/timer.rb
|
| Parent: | Object |
class representing individual timed action
| next | [RW] | Time when the Action should be called next |
Options are:
| start: | Time when the Action should be run for the first time. Repeatable Actions will be repeated after that, see :period. One-time Actions will not (obviously) Default: Time.now + :period |
| period: | How often repeatable Action should be run, in seconds. Default: 1 |
| blocked: | if true, Action starts as blocked (i.e. will stay dormant until unblocked) |
| args: | Arguments to pass to the Action callback. Default: [] |
| repeat: | Should the Action be called repeatedly? Default: false |
| code: | You can specify the Action body using &block, or using this option. |
# File lib/rbot/timer.rb, line 43
43: def initialize(options = {}, &block)
44: opts = {
45: :period => 1,
46: :blocked => false,
47: :args => [],
48: :repeat => false
49: }.merge(options)
50:
51: @block = nil
52: debug("adding timer #{self} :period => #{opts[:period]}, :repeat => #{opts[:repeat].inspect}")
53: self.configure(opts, &block)
54: debug("added #{self}")
55: end
Provides for on-the-fly reconfiguration of the Actions Accept the same arguments as the constructor
# File lib/rbot/timer.rb, line 59
59: def configure(opts = {}, &block)
60: @period = opts[:period] if opts.include? :period
61: @blocked = opts[:blocked] if opts.include? :blocked
62: @repeat = opts[:repeat] if opts.include? :repeat
63:
64: if block_given?
65: @block = block
66: elsif opts[:code]
67: @block = opts[:code]
68: end
69:
70: raise 'huh?? blockless action?' unless @block
71: if opts.include? :args
72: @args = Array === opts[:args] ? opts[:args] : [opts[:args]]
73: end
74:
75: if opts[:start] and (Time === opts[:start])
76: self.next = opts[:start]
77: else
78: self.next = Time.now + (opts[:start] || @period)
79: end
80: end
calls the Action callback, resets .next to the Time of the next call, if the Action is repeatable.
# File lib/rbot/timer.rb, line 103
103: def run(now = Time.now)
104: raise 'inappropriate time to run()' unless self.next && self.next <= now
105: self.next = nil
106: begin
107: @block.call(*@args)
108: rescue Exception => e
109: error "Timer action #{self.inspect}: block #{@block.inspect} failed!"
110: error e.pretty_inspect
111: debug e.backtrace.join("\n")
112: end
113:
114: if @repeat && @period > 0
115: self.next = now + @period
116: end
117:
118: return self.next
119: end