Class: HTTPX::Timers

Inherits:
Object
  • Object
show all
Defined in:
lib/httpx/timers.rb

Defined Under Namespace

Classes: Timer

Instance Method Summary collapse

Constructor Details

#initializeTimers

Returns a new instance of Timers.


5
6
7
# File 'lib/httpx/timers.rb', line 5

def initialize
  @intervals = []
end

Instance Method Details

#after(interval_in_secs, cb = nil, &blk) ⇒ Object

Raises:


9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/httpx/timers.rb', line 9

def after(interval_in_secs, cb = nil, &blk)
  callback = cb || blk

  raise Error, "timer must have a callback" unless callback

  # I'm assuming here that most requests will have the same
  # request timeout, as in most cases they share common set of
  # options. A user setting different request timeouts for 100s of
  # requests will already have a hard time dealing with that.
  unless (interval = @intervals.bsearch { |t| t.interval == interval_in_secs })
    interval = Interval.new(interval_in_secs)
    @intervals << interval
    @intervals.sort!
  end

  interval << callback

  @next_interval_at = nil

  Timer.new(interval, callback)
end

#fire(error = nil) ⇒ Object


41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/httpx/timers.rb', line 41

def fire(error = nil)
  raise error if error && error.timeout != @intervals.first
  return if @intervals.empty? || !@next_interval_at

  elapsed_time = Utils.elapsed_time(@next_interval_at)

  drop_elapsed!(elapsed_time)

  @intervals = @intervals.drop_while { |interval| interval.elapse(elapsed_time) <= 0 }

  @next_interval_at = nil if @intervals.empty?
end

#wait_intervalObject


31
32
33
34
35
36
37
38
39
# File 'lib/httpx/timers.rb', line 31

def wait_interval
  drop_elapsed!

  return if @intervals.empty?

  @next_interval_at = Utils.now

  @intervals.first.interval
end