Sidekiq重试作业计数 [英] Sidekiq retry count in job
问题描述
是否可以获取当前作业的重试计数?
Is there a way to get the retry count for the current job?
我希望作业在x重试后停止,而不是崩溃.我想在perform方法中询问重试次数,这样我就可以简单地返回重试次数是否等于x.
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
使用Sidekiq 2.12.
Using Sidekiq 2.12.
我(不是OP)有相同的问题,但原因有所不同.如果要重试该作业,我想进行其他检查,以确保需要该作业,如果不再期望成功,则要退出重试,因为自从排队以来,外部发生了变化.
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.
推荐答案
这可以通过添加sidekiq中间件来将msg ['retry_count']设置为作业类的实例变量来实现.
This can be accomplished by adding a sidekiq middleware to set the msg['retry_count'] as an instance variable of the job class.
添加中间件(在Rails中,通常是/config/initializers/
文件夹中的文件),如下所示:
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
您的工作:
include Sidekiq::Worker
attr_accessor :retry_count
def retry_count
@retry_count || 0
end
def perform(args)
return if retry_count > 5
...
end
这篇关于Sidekiq重试作业计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!