Skip to content

tlopo-ruby/tlopo-retry

Repository files navigation

tlopo-retry

Gem Version Build Status Code Climate Dependency Status Coverage Status

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

  1. Fork it ( https://github.com/tlopo-ruby/tlopo-retry/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Test your changes with rake test rubocop, add new tests if needed.
  4. If you added a new functionality, add it to README
  5. Commit your changes (git commit -am 'Add some feature')
  6. Push to the branch (git push origin my-new-feature)
  7. 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

About

A reusable retry mechanism which supports exponential backoff

Resources

License

MIT, MIT licenses found

Licenses found

MIT
LICENSE
MIT
LICENSE.txt

Stars

Watchers

Forks

Packages

No packages published

Languages