Skip to content

Instantly share code, notes, and snippets.

@bpot
Created May 14, 2010 19:54
Show Gist options
  • Save bpot/401579 to your computer and use it in GitHub Desktop.
Save bpot/401579 to your computer and use it in GitHub Desktop.
# Implementation of Timeout with EventMachine timers
require 'timeout'
module EMTimeout
# TODO make sure EM is running and make sure this isn't called by the reactor thread
def timeout(sec, klass = nil)
return yield if sec == nil or sec.zero?
raise ThreadError, "timeout within critical session" if Thread.critical
exception = klass || Class.new(ExitException)
x = Thread.current
t = EM.add_timer(sec) {
x.raise exception, "execution expired" if x.alive?
}
yield sec
EM.delete_timer t
end
end
if __FILE__ == $0
Thread.new { EM.run {} }
p timeout(5) {
45
}
p timeout(5, TimeoutError) {
45
}
p timeout(nil) {
54
}
p timeout(0) {
54
}
p timeout(5) {
loop {
p 10
sleep 1
}
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment