class Timers::Group
A collection of timers which may fire at different times
Attributes
Scheduled events:
Paused timers:
Active timers:
Public Class Methods
# File lib/timers/group.rb, line 38 def initialize @events = Events.new @timers = Set.new @paused_timers = Set.new @interval = Interval.new @interval.start end
Public Instance Methods
Call the given block after the given interval. The first argument will be the time at which the group was asked to fire timers for.
# File lib/timers/group.rb, line 59 def after(interval, &block) Timer.new(self, interval, false, &block) end
Cancel all timers.
# File lib/timers/group.rb, line 138 def cancel @timers.dup.each(&:cancel) end
The group's current time.
# File lib/timers/group.rb, line 143 def current_offset @interval.to_f end
Delay all timers.
# File lib/timers/group.rb, line 131 def delay(seconds) @timers.each do |timer| timer.delay(seconds) end end
Call the given block periodically at the given interval. The first argument will be the time at which the group was asked to fire timers for.
# File lib/timers/group.rb, line 72 def every(interval, recur = true, &block) Timer.new(self, interval, recur, &block) end
Fire all timers that are ready.
# File lib/timers/group.rb, line 114 def fire(offset = current_offset) @events.fire(offset) end
Call the given block immediately, and then after the given interval. The first argument will be the time at which the group was asked to fire timers for.
# File lib/timers/group.rb, line 65 def now_and_after(interval, &block) yield after(interval, &block) end
Call the given block immediately, and then periodically at the given interval. The first argument will be the time at which the group was asked to fire timers for.
# File lib/timers/group.rb, line 78 def now_and_every(interval, recur = true, &block) yield every(interval, recur, &block) end
Pause all timers.
# File lib/timers/group.rb, line 119 def pause @timers.dup.each(&:pause) end
Resume all timers.
# File lib/timers/group.rb, line 124 def resume @paused_timers.dup.each(&:resume) end
Wait
for the next timer and fire it. Can take a block, which should behave like sleep(n), except that n may be nil (sleep forever) or a negative number (fire immediately after return).
# File lib/timers/group.rb, line 86 def wait if block_given? yield wait_interval while (interval = wait_interval) && interval > 0 yield interval end else while (interval = wait_interval) && interval > 0 # We cannot assume that sleep will wait for the specified time, it might be +/- a bit. sleep interval end end fire end
Interval
to wait until when the next timer will fire.
-
nil: no timers
-
-ve: timers expired already
-
0: timers ready to fire
-
+ve: timers waiting to fire
# File lib/timers/group.rb, line 108 def wait_interval(offset = current_offset) handle = @events.first handle.time - Float(offset) if handle end