Class: NSQ::BackoffTimer

Inherits:
Object
  • Object
show all
Defined in:
lib/nsq/backoff_timer.rb

Overview

This is a timer that is smart about backing off exponentially when there are problems

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(min_interval, max_interval, ratio = 0.25, short_length = 10, long_length = 250) ⇒ BackoffTimer

Returns a new instance of BackoffTimer.



8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/nsq/backoff_timer.rb', line 8

def initialize(min_interval, max_interval, ratio=0.25, short_length=10, long_length=250)
  @min_interval    = min_interval.to_f
  @max_interval    = max_interval.to_f
  ratio            = ratio.to_f

  @max_short_timer = (@max_interval - @min_interval) * ratio
  @max_long_timer  = (@max_interval - @min_interval) * (1.0 - ratio)
  @short_unit      = @max_short_timer / short_length
  @long_unit       = @max_long_timer / long_length

  @short_interval  = 0.0
  @long_interval   = 0.0
end

Instance Attribute Details

#long_intervalObject (readonly)

Returns the value of attribute long_interval.



6
7
8
# File 'lib/nsq/backoff_timer.rb', line 6

def long_interval
  @long_interval
end

#max_intervalObject (readonly)

Returns the value of attribute max_interval.



6
7
8
# File 'lib/nsq/backoff_timer.rb', line 6

def max_interval
  @max_interval
end

#min_intervalObject (readonly)

Returns the value of attribute min_interval.



6
7
8
# File 'lib/nsq/backoff_timer.rb', line 6

def min_interval
  @min_interval
end

#short_intervalObject (readonly)

Returns the value of attribute short_interval.



6
7
8
# File 'lib/nsq/backoff_timer.rb', line 6

def short_interval
  @short_interval
end

Instance Method Details

#failureObject

Update the timer to reflect a failed call



31
32
33
34
35
36
# File 'lib/nsq/backoff_timer.rb', line 31

def failure
  @short_interval += @short_unit
  @long_interval  += @long_unit
  @short_interval  = [@short_interval, @max_short_timer].min
  @long_interval   = [@long_interval, @max_long_timer].min
end

#intervalObject

Return the interval to wait based on the successes and failures



39
40
41
# File 'lib/nsq/backoff_timer.rb', line 39

def interval
  @min_interval + @short_interval + @long_interval
end

#successObject

Update the timer to reflect a successful call



23
24
25
26
27
28
# File 'lib/nsq/backoff_timer.rb', line 23

def success
  @short_interval -= @short_unit
  @long_interval  -= @long_unit
  @short_interval  = [@short_interval, 0.0].max
  @long_interval   = [@long_interval, 0.0].max
end