class HTTPClient::TimeoutScheduler

Public Class Methods

new() click to toggle source

Creates new TimeoutScheduler.

# File lib/httpclient/timeout.rb, line 57
def initialize
  @pool = {}
  @next = nil
  @thread = start_timer_thread
end

Public Instance Methods

cancel(period) click to toggle source

Cancels the given period.

# File lib/httpclient/timeout.rb, line 79
def cancel(period)
  @pool.delete(period)
  period.cancel
end
register(thread, sec, ex) click to toggle source

Registers new timeout period.

# File lib/httpclient/timeout.rb, line 64
def register(thread, sec, ex)
  period = Period.new(thread, Time.now + sec, ex || ::Timeout::Error)
  @pool[period] = true
  if @next.nil? or period.time < @next
    begin
      @thread.wakeup
    rescue ThreadError
      # Thread may be dead by fork.
      @thread = start_timer_thread
    end
  end
  period
end

Private Instance Methods

start_timer_thread() click to toggle source
# File lib/httpclient/timeout.rb, line 86
def start_timer_thread
  thread = Thread.new {
    while true
      if @pool.empty?
        @next = nil
        sleep
      else
        min, = @pool.min { |a, b| a[0].time <=> b[0].time }
        @next = min.time
        sec = @next - Time.now
        if sec > 0
          sleep(sec)
        end
      end
      now = Time.now
      @pool.keys.each do |period|
        if period.time < now
          period.raise('execution expired')
          cancel(period)
        end
      end
    end
  }
  Thread.pass while thread.status != 'sleep'
  thread
end