Module: TimeoutEx

Defined in:
lib/timeout_ex.rb

Defined Under Namespace

Classes: Error

Class Method Summary collapse

Class Method Details

.timeout(sec, exception = Error, mutex = nil, &block) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/timeout_ex.rb', line 17

def timeout(sec, exception=Error, mutex=nil, &block)
  if sec > 0
    thread = Thread.new(mutex) do |mutex|
      Thread.current[:timeout_mutex] = mutex
      block[]
    end
    sleep(sec)
    if thread.alive?
      unless mutex.nil?
        mutex.synchronize { thread.kill if thread.alive? }
      else
        thread.kill
      end
      raise(exception, 'execution expired')
    end
  else
    block[]
  end
  true
end