Class: IO::Event::Timers

Inherits:
Object
  • Object
show all
Defined in:
lib/io/event/timers.rb

Defined Under Namespace

Classes: Handle

Instance Method Summary collapse

Constructor Details

#initializeTimers

Returns a new instance of Timers.



41
42
43
44
# File 'lib/io/event/timers.rb', line 41

def initialize
	@heap = PriorityHeap.new
	@scheduled = []
end

Instance Method Details

#after(timeout, &block) ⇒ Object



59
60
61
# File 'lib/io/event/timers.rb', line 59

def after(timeout, &block)
	schedule(now + timeout, block)
end

#fire(now = self.now) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/io/event/timers.rb', line 79

def fire(now = self.now)
	# Flush scheduled timers into the heap:
	flush!
	
	# Get the earliest timer:
	while handle = @heap.peek
		if handle.cancelled?
			@heap.pop
		elsif handle.offset <= now
			# Remove the earliest timer from the heap:
			@heap.pop
			
			# Call the block:
			handle.call(now)
		else
			break
		end
	end
end

#nowObject



75
76
77
# File 'lib/io/event/timers.rb', line 75

def now
	::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
end

#schedule(offset, block) ⇒ Object



52
53
54
55
56
57
# File 'lib/io/event/timers.rb', line 52

def schedule(offset, block)
	handle = Handle.new(offset, block)
	@scheduled << handle
	
	return handle
end

#sizeObject



46
47
48
49
50
# File 'lib/io/event/timers.rb', line 46

def size
	flush!
	
	return @heap.size
end

#wait_interval(now = self.now) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
# File 'lib/io/event/timers.rb', line 63

def wait_interval(now = self.now)
	flush!
	
	while handle = @heap.peek
		if handle.cancelled?
			@heap.pop
		else
			return handle.offset - now
		end
	end
end