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.



53
54
55
56
57
58
# File 'lib/timers/events.rb', line 53

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.



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

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.



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

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.



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

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.



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

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