Class: Timers::Events

Inherits:
Object
  • Object
show all
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

Constructor Details

#initializeEvents



48
49
50
51
52
# File 'lib/timers/events.rb', line 48

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.



84
85
86
87
88
# File 'lib/timers/events.rb', line 84

def fire(time)
  pop(time).reverse_each do |handle|
    handle.fire(time)
  end
end

#firstObject

Returns the first non-cancelled handle.



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

def first
  while handle = @sequence.last
    if handle.cancelled?
      @sequence.pop
    else
      return handle
    end
  end
  # @sequence.reverse.find { |handle| !handle.cancelled? }
end

#schedule(time, callback) ⇒ Object

Add an event at the given time.



55
56
57
58
59
60
61
62
63
64
# File 'lib/timers/events.rb', line 55

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)
  
  return handle
end

#sizeObject

Returns the number of pending (possibly cancelled) events.



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

def size
  @sequence.size
end