| 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: begin
60: sleep sec
61: rescue => e
62: x.raise e
63: else
64: x.raise exception, "execution expired" if x.alive?
65: end
66: }
67: yield sec
68: # return true
69: rescue exception => e
70: rej = /\A#{Regexp.quote(__FILE__)}:#{__LINE__-4}\z/o
71: (bt = e.backtrace).reject! {|m| rej =~ m}
72: level = -caller(CALLER_OFFSET).size
73: while THIS_FILE =~ bt[level]
74: bt.delete_at(level)
75: level += 1
76: end
77: raise if klass # if exception class is specified, it
78: # would be expected outside.
79: raise Error, e.message, e.backtrace
80: ensure
81: if y and y.alive?
82: y.kill
83: y.join # make sure y is dead.
84: end
85: end
86: end