tlopo-retry
A reusable retry mechanism which supports exponential backoff
Installation
A simple gem install tlopo-retry
will do
Usage
Retry accepts 4 parameters:
-
tries
: number of attempts, default:3
-
interval
: time in between attempts in seconds, default:1
(float is accepted but be aware of it's effect when using exponential backoff) -
error_types
: a list of error types to retry on, default:[StandardError]
-
exponential_backoff
: when true the interval will be raised to the power of current count, default:false
Full retry usage
require 'socket'
require 'logger'
require 'tlopo/retry'
LOGGER = Logger.new $stdout
count = 1
Tlopo::Retry.new(tries: 3, interval: 2, exponential_backoff: true, error_types: [ IO::TimeoutError ]).run do
LOGGER.info "Trying #{count}"
count += 1
TCPSocket.new('www.google.co.uk','8080', connect_timeout: 1).close
end
Tips
Float interval < 1 with exponential backoff
It may not be intuitive, but when using a float less than 1 for the interval together with exponential_backoff, the time to sleep will be shorter at every run:
ruby -e 'interval=0.5; (1..5).each{|count| puts interval ** count}'
0.5
0.25
0.125
0.0625
0.03125
Usage Styles
Retry supports 3 usage styles: Keyword args, Fluent (method chaining) and DSL:
kwargs:
Tlopo::Retry.new(tries: 3, interval: 2, exponential_backoff: true, error_types: [ SomeError, SomeError2 ]).run do
do_something
end
Fluent:
Tlopo::Retry.new.tries(3).interval(2).exponential_backoff(true).error_types([SomeError, SomeError2]).run do
do_something
end
DSL:
Tlopo::Retry.new.run do
tries 3
interval 2
exponential_backoff true
error_types [SomeError, SomeError2]
do_something
end
Contributing
- Fork it ( https://github.com/tlopo-ruby/tlopo-retry/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Test your changes with
rake test rubocop
, add new tests if needed. - If you added a new functionality, add it to README
- Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
Tests
This library is tested with Minitest. Please run all tests before submitting a Pull Request, and add new tests for new functionality.
Running tests:
rake test