8 # status = Timeout::timeout(5) {
9 # # Something that should be interrupted if it takes too much time...
14 # A way of performing a potentially long-running operation in a thread, and terminating
15 # it's execution if it hasn't finished by a fixed amount of time.
17 # Previous versions of timeout didn't provide use a module for namespace. This version
18 # provides both Timeout.timeout, and a backwards-compatible #timeout.
22 # Copyright:: (C) 2000 Network Applied Communication Laboratory, Inc.
23 # Copyright:: (C) 2000 Information-technology Promotion Agency, Japan
26 # Raised by Timeout#timeout when the block times out.
27 class Error < RuntimeError
29 class ExitException < ::Exception # :nodoc:
32 THIS_FILE = /\A#{Regexp.quote(__FILE__)}:/o
33 CALLER_OFFSET = ((c = caller[0]) && THIS_FILE =~ c) ? 1 : 0
35 # Executes the method's block. If the block execution terminates before
36 # +sec+ seconds has passed, it returns the result value of the block.
37 # If not, it terminates the execution and raises +exception+ (which defaults
40 # Note that this is both a method of module Timeout, so you can 'include Timeout'
41 # into your classes so they have a #timeout method, as well as a module method,
42 # so you can call it directly as Timeout.timeout().
43 def timeout(sec, klass = nil) #:yield: +sec+
44 return yield(sec) if sec == nil or sec.zero?
45 exception = klass || Class.new(ExitException)
50 x.raise exception, "execution expired" if x.alive?
54 rej = /\A#{Regexp.quote(__FILE__)}:#{__LINE__-4}\z/o
55 (bt = e.backtrace).reject! {|m| rej =~ m}
56 level = -caller(CALLER_OFFSET).size
57 while THIS_FILE =~ bt[level]
61 raise if klass # if exception class is specified, it
62 # would be expected outside.
63 raise Error, e.message, e.backtrace
67 y.join # make sure y is dead.
72 module_function :timeout
77 # Timeout::timeout(n, e, &block).
79 # Defined for backwards compatibility with earlier versions of timeout.rb, see
81 def timeout(n, e = nil, &block)
82 Timeout::timeout(n, e, &block)
85 # Another name for Timeout::Error, defined for backwards compatibility with
86 # earlier versions of timeout.rb.
87 TimeoutError = Timeout::Error
93 p timeout(5, TimeoutError) {