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

Returns a new instance of Events.



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

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

Instance Method Details

#fire(time) ⇒ Object

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



100
101
102
103
104
105
106
107
# File 'lib/timers/events.rb', line 100

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

#firstObject

Returns the first non-cancelled handle.



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

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

#schedule(time, callback) ⇒ Object

Add an event at the given time.



76
77
78
79
80
81
82
# File 'lib/timers/events.rb', line 76

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.



95
96
97
# File 'lib/timers/events.rb', line 95

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