Class: Timers::Events

Inherits:
Object
  • Object
show all
Defined in:
lib/timers/events.rb

Overview

Maintains a PriorityHeap of events ordered on time, which can be cancelled.

Defined Under Namespace

Classes: Handle

Instance Method Summary collapse

Constructor Details

#initializeEvents



51
52
53
54
55
56
# File 'lib/timers/events.rb', line 51

def initialize
  # A sequence of handles, maintained in sorted order, future to present.
  # @sequence.last is the next event to be fired.
  @sequence = PriorityHeap.new
  @queue = []
end

Instance Method Details

#fire(time) ⇒ Object

Fire all handles for which Handle#time is less than the given time.



85
86
87
88
89
90
91
92
# File 'lib/timers/events.rb', line 85

def fire(time)
  merge!
  
  while handle = @sequence.peek and handle.time <= time
    @sequence.pop
    handle.fire(time)
  end
end

#firstObject

Returns the first non-cancelled handle.



70
71
72
73
74
75
76
77
# File 'lib/timers/events.rb', line 70

def first
  merge!
  
  while (handle = @sequence.peek)
    return handle unless handle.cancelled?
    @sequence.pop
  end
end

#schedule(time, callback) ⇒ Object

Add an event at the given time.



59
60
61
62
63
64
65
66
67
# File 'lib/timers/events.rb', line 59

def schedule(time, callback)
  flush!
  
  handle = Handle.new(time.to_f, callback)
  
  @queue << handle
  
  return handle
end

#sizeObject

Returns the number of pending (possibly cancelled) events.



80
81
82
# File 'lib/timers/events.rb', line 80

def size
  @sequence.size + @queue.size
end