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

Returns a new instance of Events.



63
64
65
66
67
68
# File 'lib/timers/events.rb', line 63

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.



95
96
97
98
99
100
101
102
# File 'lib/timers/events.rb', line 95

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.



80
81
82
83
84
85
86
87
# File 'lib/timers/events.rb', line 80

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.



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

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

#sizeObject

Returns the number of pending (possibly cancelled) events.



90
91
92
# File 'lib/timers/events.rb', line 90

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