Skip to content

Instantly share code, notes, and snippets.

@seeARMS
Forked from usahg/exponential_backoff.rb
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seeARMS/a4fe843fbc01a97acdfc to your computer and use it in GitHub Desktop.
Save seeARMS/a4fe843fbc01a97acdfc to your computer and use it in GitHub Desktop.
# Exponential backoff using Ruby lambdas
#
# Continuously retry sending a request at exponentially increasing
# values, with a top at 1 second
num_retries = 5
exp_backoff = ->(i) { [1, (0.5 * (2.0**(i/2.0) - 1.0))].min }
# stores the delays
(delays ||= [ ]) << (1..num_retries).map(&exp_backoff)
begin
req = Net::HTTP.get('http://google.com')
rescue StandardError, TimeoutError => e
if delay = delays.shift
sleep delay
retry
else
raise StandardError, "Unable to retrieve website: #{e.message}"
end
end
puts retries
# [0.2, 0.5, 0.9, 1, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment