class Reattempt::Backoff

Calculate exponential backoff times between min_delay and max_delay, with jitter of between 0 and 1 and factor of, by default, 2.

Minimum delay is min_delay * jitter / 2, maximum is max_delay * jitter / 2.

Instances are Enumerable.

Example:

“`ruby # Start delay 0.075-0.125 seconds, doubling to a limit of 0.75-1.25 bo = Reattempt::Backoff.new(min_delay: 0.1, max_delay: 1.0, jitter: 0.5) bo.take(4).map { |x| x.round(4) } # => [0.1151, 0.1853, 0.4972, 0.9316] “`

Public Instance Methods

[](try)
Alias for: delay_for_attempt
delay_for_attempt(try) click to toggle source

Calculate a randomised delay for attempt number try, starting from 0.

Aliased to []

# File lib/reattempt.rb, line 60
def delay_for_attempt(try)
  delay = (min_delay * (factor ** try)).clamp(min_delay, max_delay)
  delay * Random.rand(jitter_range)
end
Also aliased as: []
each() { |delay_for_attempt(try)| ... } click to toggle source

Iterate over calls to delay_for_attempt with a counter. If no block given, return an Enumerator.

# File lib/reattempt.rb, line 49
def each
  return enum_for(:each) unless block_given?

  0.upto(Float::INFINITY) do |try|
    yield delay_for_attempt(try)
  end
end

Private Instance Methods

jitter_range() click to toggle source
# File lib/reattempt.rb, line 69
def jitter_range
  @jitter_range ||= Range.new(1 - (jitter / 2), 1 + jitter / 2)
end