9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

リトライ処理を疎結合にできる retriable gem の使用例

Posted at

次のコードは、

retries = 0
begin
  1 / 0 if retries < 2
  puts "ok"
rescue => exception
  raise if retries >= 2
  sleep(0.5 * 1.5**retries)
  retries += 1
  puts "#{retries}回目のリトライ"
  retry
end
# >> 1回目のリトライ
# >> 2回目のリトライ
# >> ok

retriable gem で次のように置き換えることができます。

require "retriable"

Retriable.configure do |c|
  c.base_interval = 0.5
  c.multiplier = 1.5
  c.on_retry = -> exception, try, elapsed_time, interval {
    puts "#{try}回目のリトライ"
  }
end

Retriable.retriable do |i|
  1 / 0 if i <= 2
  puts "ok"
end
# >> 1回目のリトライ
# >> 2回目のリトライ
# >> ok
9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?