forked from eventmachine/eventmachine
-
Notifications
You must be signed in to change notification settings - Fork 4
/
timers.rb
56 lines (51 loc) · 1.25 KB
/
timers.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
module EventMachine
# Creates a one-time timer
#
# timer = EventMachine::Timer.new(5) do
# # this will never fire because we cancel it
# end
# timer.cancel
#
class Timer
# Create a new timer that fires after a given number of seconds
def initialize interval, callback=nil, &block
@signature = EventMachine::add_timer(interval, callback || block)
end
# Cancel the timer
def cancel
EventMachine.send :cancel_timer, @signature
end
end
# Creates a periodic timer
#
# n = 0
# timer = EventMachine::PeriodicTimer.new(5) do
# puts "the time is #{Time.now}"
# timer.cancel if (n+=1) > 5
# end
#
class PeriodicTimer
# Create a new periodic timer that executes every interval seconds
def initialize interval, callback=nil, &block
@interval = interval
@code = callback || block
@cancelled = false
schedule
end
# Cancel the periodic timer
def cancel
@cancelled = true
end
# Fire the timer every interval seconds
attr_accessor :interval
def schedule # :nodoc:
EventMachine::add_timer @interval, proc {self.fire}
end
def fire # :nodoc:
unless @cancelled
@code.call
schedule
end
end
end
end