Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set retry count for Sidekiq with ActiveJob?

From the Rails API, I found ActiveJob can retry_job interval:

my_job_instance.enqueue
my_job_instance.enqueue wait: 5.minutes
my_job_instance.enqueue queue: :important
my_job_instance.enqueue wait_until: Date.tomorrow.midnight

http://api.rubyonrails.org/classes/ActiveJob/Enqueuing.html

But if I want to set retry count, such as Sidekiq's:

include Sidekiq::Worker
sidekiq_options :retry => 5

https://github.com/mperham/sidekiq/wiki/Error-Handling

How to do in this sample code?

class SiteScrapperJob < ActiveJob::Base
  rescue_from(ErrorLoadingSite) do
    retry_job queue: :low_priority
  end

  def perform(*args)
    # raise ErrorLoadingSite if cannot scrape
  end
end

Now I added this to my job class:

Sidekiq.default_worker_options = { retry: 5 }

But it seems not very good.

like image 561
scho Avatar asked Oct 15 '15 01:10

scho


2 Answers

As of Sidekiq 6.0.4 you can use sidekiq_options in an ActiveJob to set the retry option.

like image 158
Mike Perham Avatar answered Nov 03 '22 22:11

Mike Perham


You also might be interested in this solution which uses serialize and deserialize api to store the number of attempts.

class DeliverWebhookJob < ActiveJob::Base
  def serialize
    super.merge('attempt_number' => (@attempt_number || 0) + 1)
  end

  def deserialize(job_data)
    super
    @attempt_number = job_data['attempt_number']
  end

  rescue_from(ErrorLoadingSite) do |exception|
    retry_job(wait: 10) if @attempt_number < 5
  end

  def perform(*args)
    # raise ErrorLoadingSite if cannot scrape
  end
end

Take it from here.

like image 19
Vini Oliveira Avatar answered Nov 04 '22 00:11

Vini Oliveira