Module: ProcessLock::ExecuteWithRetry

Included in:
WithProcessLock
Defined in:
lib/process_lock/execute_with_retry.rb

Instance Method Summary collapse

Instance Method Details

#execute_with_retry(key, retry_wait: 1, timeout: nil, &blk) ⇒ Object

Tries to run the given block and retries every retry_wait seconds until

the process in unblocked

Parameters:

  • key (String)

    The unique key to determine if the process is locked

  • retry_wait (Number) (defaults to: 1)

    The number of seconds to wait in between retry attempts, defaulting to 1

  • timeout (Number) (defaults to: nil)

    The number of seconds until an exception should be raised instead of retrying, defaulting to nil (no timeout)



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/process_lock/execute_with_retry.rb', line 10

def execute_with_retry(
  key,
  retry_wait: 1,
  timeout: nil,
  &blk
)
  if can_execute?(key)
    execute(key, &blk)
  else
    # If there is time left before timeout or there is no timeout,
    # wait retry_wait seconds and then recurse
    if timeout.nil? || timeout >= retry_wait
      sleep(retry_wait)
      execute_with_retry(
        key,
        retry_wait: retry_wait,
        timeout: timeout.nil? ? nil : timeout - retry_wait,
        &blk
      )
    else
      # If the timeout was reached, give up
      redis.quit
      raise ProcessLockError, key: key
    end
  end
end