Last active
August 29, 2015 13:57
-
-
Save kirel/9464094 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ExponentialBackoff | |
def self.retry_with_exponential_backoff *args | |
opts = { max: 3 } | |
opts.merge!(args.pop) if args.last.is_a?(Hash) | |
attempt = 0 | |
begin | |
yield | |
rescue *args | |
if attempt < opts[:max] | |
attempt += 1 | |
puts "retrying in #{attempt**2}" | |
sleep attempt**2 | |
retry | |
else | |
raise | |
end | |
end | |
end | |
end | |
if __FILE__ == $0 | |
ExponentialBackoff.retry_with_exponential_backoff(NoMethodError, max: 2) do | |
puts nil.foo | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment