Class: Rack::Timeout::Scheduler::Timeout

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/timeout/support/timeout.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

ON_TIMEOUT =

default action to take when a timeout happens

->thr { thr.raise Error, "execution expired" }

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&on_timeout) ⇒ Timeout

initializes a timeout object with an optional block to handle the timeout differently. the block is passed the thread that’s gone overtime.



9
10
11
12
# File 'lib/rack/timeout/support/timeout.rb', line 9

def initialize(&on_timeout)
  @on_timeout = on_timeout || ON_TIMEOUT
  @scheduler  = Rack::Timeout::Scheduler.singleton
end

Class Method Details

.timeout(secs, &block) ⇒ Object

timeout method on singleton instance for when a custom on_timeout is not required



25
26
27
# File 'lib/rack/timeout/support/timeout.rb', line 25

def self.timeout(secs, &block)
  (@singleton ||= new).timeout(secs, &block)
end

Instance Method Details

#timeout(secs, &block) ⇒ Object

takes number of seconds to wait before timing out, and code block subject to time out



15
16
17
18
19
20
21
22
# File 'lib/rack/timeout/support/timeout.rb', line 15

def timeout(secs, &block)
  return block.call if secs.nil? || secs.zero?            # skip timeout flow entirely for zero or nil
  thr = Thread.current                                    # reference to current thread to be used in timeout thread
  job = @scheduler.run_in(secs) { @on_timeout.call thr }  # schedule this thread to be timed out; should get cancelled if block completes on time
  return block.call                                       # do what you gotta do
ensure                                                    #
  job.cancel! if job                                      # cancel the scheduled timeout job; if the block completed on time, this
end