class Timers::Events

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

Public Class Methods

new() click to toggle source
# 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

Public Instance Methods

fire(time) click to toggle source

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

# 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
first() click to toggle source

Returns the first non-cancelled handle.

# 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) click to toggle source

Add an event at the given time.

# File lib/timers/events.rb, line 71
def schedule(time, callback)
        handle = Handle.new(time.to_f, callback)
        
        @queue << handle
        
        return handle
end
size() click to toggle source

Returns the number of pending (possibly cancelled) events.

# File lib/timers/events.rb, line 90
def size
        @sequence.size + @queue.size
end

Private Instance Methods

merge!() click to toggle source

Move all non-cancelled timers from the pending queue to the priority heap

# File lib/timers/events.rb, line 107
def merge!
        while handle = @queue.pop
                next if handle.cancelled?
                
                @sequence.push(handle)
        end
end