ruby-on-rails - 在 Rails 中延迟重新排队作业的最佳方法是什么?

标签 ruby-on-rails ruby sidekiq software-design rails-activejob

我想在作业完成后自动重新排队。如果没有任何处理,将有 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/

相关文章:

ruby - 检查 DataMapper(或其他 ORM)模型是否持久化

ruby-on-rails - 使用 cronjob 定期重新启动 sidekiq

ruby-on-rails - 构建异步邮件程序的最佳实践(使用 Sidekiq)

ruby-on-rails - Rails 3.1 博客的帖子/评论模型 -- 如何通过 ajax 提交评论?

ruby-on-rails - 为什么 Rails 4 测试不重置数据库

ruby-on-rails - 如何限制模型每天创建一条记录?

ruby-on-rails - Errno::EIO: 输入/输出错误 - <STDOUT>

ruby-on-rails - Ruby << 语法方法会引发错误,但 .push 方法不会在使用 yield 时引发错误。为什么?

ruby-on-rails - Rails 3.1 引擎的 Assets

ruby - 使用两个数组Ruby构造hash