我想在作业完成后自动重新排队。如果没有任何处理,将有 10 秒的可选延迟。
我可以看到两种方法。第一个是将逻辑放在 perform
block 中。第二种是使用 around_block
功能来做到这一点。
更优雅的方法是什么?
这是一个具有这种逻辑的代码块示例
# Process queue automatically
class ProcessingJob < ApplicationJob
queue_as :processing_queue
around_perform do |_job, block|
if block.call.zero?
# wait for 10 seconds if 0 items was handled
self.class.set(wait: 10.seconds).perform_later
else
# don't rest, there are many work to do
self.class.perform_later
end
end
def perform
# will return number of processed items
ProcessingService.handle_next_batch
end
end
我是否应该将 around_block
逻辑放入 perform
函数中?
最佳答案
def perform
# will return number of processed items
processed_items_count = ProcessingService.handle_next_batch
delay_for_next_job = processed_items_count.zero? ? 10 : 0
next_job = self.class.set(wait: delay_for_next_job.seconds)
next_job.perform_later
end
您可以将 delay_for_next_job 提取为私有(private)方法等,根据需要应用重构。
为什么要使用around_perform
?您在这里不需要工作实例。
根据您的需要,您还可以使用类似 https://github.com/mhenrixon/sidekiq-unique-jobs 的方式检查当前是否有任何作业正在等待处理。 (抱歉,我不太熟悉 ActiveJob API)
关于ruby-on-rails - 在 Rails 中延迟重新排队作业的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58313299/