Skip to content

Instantly share code, notes, and snippets.

@glejeune
Created December 22, 2009 17:46
Show Gist options
  • Save glejeune/261900 to your computer and use it in GitHub Desktop.
Save glejeune/261900 to your computer and use it in GitHub Desktop.
A very very simple timer
require 'rubygems'
require 'eventmachine'
class Timer
def initialize
@run = false
@timeout_proc = nil
end
# Run <tt>blk</tt> every <tt>every</tt> seconds during <tt>during</tt> seconds
def self.start( every = 1, during = 5, &blk )
t = Timer.new()
t.start( every, during, &blk )
end
# Run <tt>blk</tt> every <tt>every</tt> seconds during <tt>during</tt> seconds
def start( every = 1, during = 5, &blk )
@run = true
Thread.new do
time = Time.now
EventMachine.run do
reschedule = proc { |inc, block|
if Time.now - time > during
self.stop
@timeout_proc.call unless @timeout_proc.nil?
else
@timer = EM.add_timer(inc) { reschedule.call(inc, block) }
block.call
end
}
@timer = EM.add_timer(every) { reschedule.call(every, blk) }
blk.call
end
end
return self
end
# Timeout !
def timeout( &blk )
@timeout_proc = blk
return self
end
# Stop the timer
def stop
EM.stop_event_loop if @run
@run = false
return self
end
end
## Example
if $0 == __FILE__
t = Timer.start(5, 20) {
puts "Please, give me your name..."
}.timeout {
puts "Too late rabbit !!!"
exit 0
}
r = $stdin.readline
puts "Hello #{r}"
t.stop
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment