Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lleirborras/1270499 to your computer and use it in GitHub Desktop.
Save lleirborras/1270499 to your computer and use it in GitHub Desktop.
retry_upto.rb
# Ruby `retry` with steroids:
#
# - retry up to 5 times without waiting between them and retrying after any exception
#
# retry_upto(5) do ... end
#
# - retry up to 5 times, waiting 2 seconds between retries and retrying after any exception
#
# retry_upto(5, :wait => 2) do ... end
#
# - retry up to 5 times, waiting 1 second initially and having increasing patience (2, 4, 8, ...)
#
# retry_upto(5, :wait => 1, :patience => 2) do ... end
#
# - retry up to 5 times, waiting 1 second initially and having decreasing patience (0.5, 0.25, 0.125, ...)
#
# retry_upto(5, :wait => 1, :patience => 0.5) do ... end
#
# - retry up to 5 times without waiting between retries, retrying only after a ZeroDivisionError
#
# retry_upto(5, :rescue_only => ZeroDivisionError) do ... end
#
# - retry up to 5 times, waiting 2 seconds between retries, retrying only after a ZeroDivisionError
#
# retry_upto(5, :wait => 2, :rescue_only => ZeroDivisionError) do ... end
def retry_upto(max_retries = 1, options = {})
begin
return yield if ((max_retries -= 1) > 0)
rescue (options[:rescue_only] || Exception)
sleep((options[:wait] || 0) * (options[:patience] || 1))
retry
end
yield
end
@lleirborras
Copy link
Author

Just some compact coding

@jaimeiniesta
Copy link

nice!

@jaimeiniesta
Copy link

mmm, this wouldn't make a cumulative series. If we pass in :wait => 1, :patience => 2, it should wait 2, 4, 8, 16...

but in your example it will wait 2, 2, 2, 2...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment