Class: Timers::Events
- Inherits:
-
Object
- Object
- Timers::Events
- Defined in:
- lib/timers/events.rb
Overview
Maintains an ordered list of events, which can be cancelled.
Defined Under Namespace
Classes: Handle
Instance Method Summary collapse
-
#fire(time) ⇒ Object
Fire all handles for which Handle#time is less than the given time.
-
#first ⇒ Object
Returns the first non-cancelled handle.
-
#initialize ⇒ Events
constructor
A new instance of Events.
-
#schedule(time, callback) ⇒ Object
Add an event at the given time.
-
#size ⇒ Object
Returns the number of pending (possibly cancelled) events.
Constructor Details
#initialize ⇒ Events
Returns a new instance of Events.
47 48 49 50 51 |
# File 'lib/timers/events.rb', line 47 def initialize # A sequence of handles, maintained in sorted order, future to present. # @sequence.last is the next event to be fired. @sequence = [] end |
Instance Method Details
#fire(time) ⇒ Object
Fire all handles for which Handle#time is less than the given time.
79 80 81 82 83 |
# File 'lib/timers/events.rb', line 79 def fire(time) pop(time).reverse_each do |handle| handle.fire(time) end end |
#first ⇒ Object
Returns the first non-cancelled handle.
66 67 68 69 70 71 |
# File 'lib/timers/events.rb', line 66 def first while (handle = @sequence.last) return handle unless handle.cancelled? @sequence.pop end end |
#schedule(time, callback) ⇒ Object
Add an event at the given time.
54 55 56 57 58 59 60 61 62 63 |
# File 'lib/timers/events.rb', line 54 def schedule(time, callback) handle = Handle.new(time.to_f, callback) index = bisect_left(@sequence, handle) # Maintain sorted order, O(logN) insertion time. @sequence.insert(index, handle) handle end |
#size ⇒ Object
Returns the number of pending (possibly cancelled) events.
74 75 76 |
# File 'lib/timers/events.rb', line 74 def size @sequence.size end |