Skip to content

Instantly share code, notes, and snippets.

@kirel
Last active August 29, 2015 13:57
Show Gist options
  • Save kirel/9464094 to your computer and use it in GitHub Desktop.
Save kirel/9464094 to your computer and use it in GitHub Desktop.
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