Module | Timeout |
In: |
lib/timeout.rb
|
A way of performing a potentially long-running operation in a thread, and terminating it‘s execution if it hasn‘t finished within fixed amount of time.
Previous versions of timeout didn‘t use a module for namespace. This version provides both Timeout.timeout, and a backwards-compatible timeout.
require 'timeout' status = Timeout::timeout(5) { # Something that should be interrupted if it takes too much time... }
THIS_FILE | = | /\A#{Regexp.quote(__FILE__)}:/o |
CALLER_OFFSET | = | ((c = caller[0]) && THIS_FILE =~ c) ? 1 : 0 |
Executes the method‘s block. If the block execution terminates before sec seconds has passed, it returns true. If not, it terminates the execution and raises exception (which defaults to Timeout::Error).
Note that this is both a method of module Timeout, so you can ‘include Timeout’ into your classes so they have a timeout method, as well as a module method, so you can call it directly as Timeout.timeout().
# File lib/timeout.rb, line 52 52: def timeout(sec, klass = nil) 53: return yield if sec == nil or sec.zero? 54: raise ThreadError, "timeout within critical session" if Thread.critical 55: exception = klass || Class.new(ExitException) 56: begin 57: x = Thread.current 58: y = Thread.start { 59: sleep sec 60: x.raise exception, "execution expired" if x.alive? 61: } 62: yield sec 63: # return true 64: rescue exception => e 65: rej = /\A#{Regexp.quote(__FILE__)}:#{__LINE__-4}\z/o 66: (bt = e.backtrace).reject! {|m| rej =~ m} 67: level = -caller(CALLER_OFFSET).size 68: while THIS_FILE =~ bt[level] 69: bt.delete_at(level) 70: level += 1 71: end 72: raise if klass # if exception class is specified, it 73: # would be expected outside. 74: raise Error, e.message, e.backtrace 75: ensure 76: y.kill if y and y.alive? 77: end 78: end