Class: EventMachine::RestartableTimer

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

Overview

Creates a restartable timer

puts "started timer at #Time.now" timer = EventMachine::RestartableTimer.new(5) do # should be about 7 seconds later, due to restart at 2 seconds puts "completed timer at #Time.now" end EventMachine::Timer.new(2) { timer.restart }

Instance Method Summary collapse

Constructor Details

#initialize(interval, callback = nil, &block) ⇒ RestartableTimer

Returns a new instance of RestartableTimer.



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

def initialize interval, callback=nil, &block
  @interval = interval
  @code = callback || block
  @done = false
  @work = method(:fire)
  schedule
end

Instance Method Details

#cancelObject

Cancel the timer



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

def cancel
  @done = true
  EventMachine.send :cancel_timer, @signature
end

#fireObject

:nodoc



98
99
100
101
102
103
# File 'lib/em/timers.rb', line 98

def fire # :nodoc
  unless @done
    @done = true
    @code.call
  end
end

#restartObject

Restart the timer



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

def restart
  unless @done
    EventMachine.send :cancel_timer, @signature
    schedule
  end
end

#scheduleObject

:nodoc



94
95
96
# File 'lib/em/timers.rb', line 94

def schedule # :nodoc
  @signature = EventMachine::add_timer(@interval, @work)
end