Sidekiq retry count in job

2020-08-15 00:41发布

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.

Edit

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.

3条回答
干净又极端
2楼-- · 2020-08-15 00:49

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
查看更多
劫难
3楼-- · 2020-08-15 00:49

you dont need to deal with this logic directly to accomplish what you want. simply add some configs to your worker as such..note the sidekiq_options . based on your comment below " prevent Sidekiq from moving the job to the dead jobs queue"

 class MyWorker  
     include Sidekiq::Worker
     sidekiq_options :retry => 5, :dead => false

      def perform
          #do some stuff
      end
 end

then the job should just retry 5 times and fail gracefully. also if you want to execute a code block once 5 retries are spent, the worker has a method called sidekiq_retries_exhausted where you could do some custom logging, etc.

查看更多
Deceive 欺骗
4楼-- · 2020-08-15 01:01

You can access the retries with the Sidekiq API:

https://github.com/mperham/sidekiq/wiki/API#retries

Find the job you need and use job['retry_count'] to get the number of retries.

查看更多
登录 后发表回答