Class: GCSLock::Utils

Inherits:
Object
  • Object
show all
Defined in:
lib/gcslock/utils.rb

Class Method Summary collapse

Class Method Details

.backoff(min_backoff:, max_backoff:, timeout: nil) ⇒ Object

Raises:


4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/gcslock/utils.rb', line 4

def backoff(min_backoff:, max_backoff:, timeout: nil)
  backoff = min_backoff

  now = Time.now
  end_time = now + timeout unless timeout.nil?

  loop do
    return true if yield
    break if !timeout.nil? && now + backoff >= end_time
    sleep(backoff)

    backoff_opts = [max_backoff, backoff * 2]

    unless timeout.nil?
      now = Time.now
      diff = end_time - now
      backoff_opts.push(diff) if diff > 0
    end

    backoff = backoff_opts.min
  end

  raise LockTimeoutError, "Backoff timed out"
end