Class: Hoodie::Timers::Events
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.
294 295 296 297 298 |
# File 'lib/hoodie/timers.rb', line 294 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.
326 327 328 329 330 |
# File 'lib/hoodie/timers.rb', line 326 def fire(time) pop(time).reverse_each do |handle| handle.fire(time) end end |
#first ⇒ Object
Returns the first non-cancelled handle.
310 311 312 313 314 315 316 317 318 |
# File 'lib/hoodie/timers.rb', line 310 def first while handle = @sequence.last if handle.cancelled? @sequence.pop else return handle end end end |
#schedule(time, callback) ⇒ Object
Add an event at the given time.
301 302 303 304 305 306 307 |
# File 'lib/hoodie/timers.rb', line 301 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.
321 322 323 |
# File 'lib/hoodie/timers.rb', line 321 def size @sequence.size end |