Sha256: ab7a569cb28413a214bb2fb5f80b4b06b6f2b42ea513f0644cec659a097e94ae

Contents?: true

Size: 1005 Bytes

Versions: 3

Compression:

Stored size: 1005 Bytes

Contents

module Retriable
  class ExponentialBackoff
    ATTRIBUTES = [
      :tries,
      :base_interval,
      :multiplier,
      :max_interval,
      :rand_factor,
    ].freeze

    attr_accessor(*ATTRIBUTES)

    def initialize(opts = {})
      @tries         = 3
      @base_interval = 0.5
      @max_interval  = 60
      @rand_factor   = 0.5
      @multiplier    = 1.5

      opts.each do |k, v|
        raise ArgumentError, "#{k} is not a valid option" if !ATTRIBUTES.include?(k)
        instance_variable_set(:"@#{k}", v)
      end
    end

    def intervals
      intervals = Array.new(tries) do |iteration|
        [base_interval * multiplier**iteration, max_interval].min
      end

      return intervals if rand_factor.zero?

      intervals.map { |i| randomize(i) }
    end

    private

    def randomize(interval)
      return interval if rand_factor.zero?
      delta = rand_factor * interval * 1.0
      min = interval - delta
      max = interval + delta
      rand(min..max)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
retriable-3.1.1 lib/retriable/exponential_backoff.rb
retriable-3.1.0 lib/retriable/exponential_backoff.rb
retriable-3.0.2 lib/retriable/exponential_backoff.rb