class Rack::Timeout::Scheduler::Timeout

Constants

ON_TIMEOUT

Public Class Methods

new(&on_timeout) click to toggle source

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

# 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
timeout(secs, &block) click to toggle source

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

# File lib/rack/timeout/support/timeout.rb, line 25
def self.timeout(secs, &block)
  (@singleton ||= new).timeout(secs, &block)
end

Public Instance Methods

timeout(secs, &block) click to toggle source

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

# 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