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.



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

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.



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

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

#firstObject

Returns the first non-cancelled handle.



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

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

#schedule(time, callback) ⇒ Object

Add an event at the given time.



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/timers/events.rb', line 56

def schedule(time, callback)
	handle = Handle.new(time.to_f, callback)

	index = bisect_left(@sequence, handle)

	if current_handle = @sequence[index] and current_handle.cancelled?
		# puts "Replacing handle at index: #{index} due to cancellation in array containing #{@sequence.size} item(s)."
		@sequence[index] = handle
	else
		# puts "Inserting handle at index: #{index} in array containing #{@sequence.size} item(s)."
		@sequence.insert(index, handle)
	end

	handle
end

#sizeObject

Returns the number of pending (possibly cancelled) events.



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

def size
	@sequence.size
end