Class: Timers
- Inherits:
-
Object
- Object
- Timers
- Extended by:
- Forwardable
- Includes:
- Enumerable
- Defined in:
- lib/timers.rb,
lib/timers/version.rb
Overview
Low precision timers implemented in pure Ruby
Defined Under Namespace
Classes: Timer
Constant Summary collapse
- VERSION =
"1.0.0"
Instance Method Summary collapse
- #add(timer) ⇒ Object
-
#after(interval, &block) ⇒ Object
Call the given block after the given interval.
-
#every(interval, &block) ⇒ Object
Call the given block periodically at the given interval.
-
#fire(now = Time.now) ⇒ Object
Fire all timers that are ready.
-
#initialize ⇒ Timers
constructor
A new instance of Timers.
-
#wait ⇒ Object
Wait for the next timer and fire it.
-
#wait_interval(now = Time.now) ⇒ Object
Interval to wait until when the next timer will fire.
Constructor Details
#initialize ⇒ Timers
Returns a new instance of Timers.
10 11 12 |
# File 'lib/timers.rb', line 10 def initialize @timers = SortedSet.new end |
Instance Method Details
#add(timer) ⇒ Object
47 48 49 50 |
# File 'lib/timers.rb', line 47 def add(timer) raise TypeError, "not a Timers::Timer" unless timer.is_a? Timers::Timer @timers.add(timer) end |
#after(interval, &block) ⇒ Object
Call the given block after the given interval
15 16 17 |
# File 'lib/timers.rb', line 15 def after(interval, &block) Timer.new(self, interval, false, &block) end |
#every(interval, &block) ⇒ Object
Call the given block periodically at the given interval
20 21 22 |
# File 'lib/timers.rb', line 20 def every(interval, &block) Timer.new(self, interval, true, &block) end |
#fire(now = Time.now) ⇒ Object
Fire all timers that are ready
39 40 41 42 43 44 45 |
# File 'lib/timers.rb', line 39 def fire(now = Time.now) time = now + 0.001 # Fudge 1ms in case of clock imprecision while (timer = @timers.first) && (time >= timer.time) @timers.delete timer timer.fire(now) end end |
#wait ⇒ Object
Wait for the next timer and fire it
25 26 27 28 29 |
# File 'lib/timers.rb', line 25 def wait i = wait_interval sleep i if i fire end |
#wait_interval(now = Time.now) ⇒ Object
Interval to wait until when the next timer will fire
32 33 34 35 36 |
# File 'lib/timers.rb', line 32 def wait_interval(now = Time.now) timer = @timers.first return unless timer timer.time - now end |