Is there a way to get the retry count for the current job?
I want the job to stop, not crash, after x retries. I would like to ask the retry count in the perform method so I could simply return if the retry count equals x.
def perform(args)
return if retry_count > 5
...
end
Using Sidekiq 2.12.
I (not the OP) have the same question but for a different reason. If the job is being retried I want to do additional sanity checking to make sure the job is needed and to quit retrying if it is no longer expected to succeed because something external changed since it was queued.
So, is there a way to get the retry count for the current job? The current answers only suggest ways you can get around needing it or can get it from outside the job.
This can be accomplished by adding a sidekiq middleware to set the msg['retry_count'] as an instance variable of the job class.
Add a middleware (in Rails, it's usually a file in /config/initializers/
folder) like so:
class SidekiqMiddleware
def call(worker, job, queue)
worker.retry_count = job['retry_count'] if worker.respond_to?(:retry_count=)
yield
end
end
Sidekiq.configure_server do |config|
config.server_middleware do |chain|
chain.add SidekiqMiddleware
end
end
In your job:
include Sidekiq::Worker
attr_accessor :retry_count
def retry_count
@retry_count || 0
end
def perform(args)
return if retry_count > 5
...
end