【问题标题】:What is the best way to re-queue job in Rails with delay?在 Rails 中延迟重新排队作业的最佳方法是什么?
【发布时间】:2020-02-07 07:57:13
【问题描述】:

我想在作业完成后自动重新排队。如果没有任何处理,将会有 10 秒的可选延迟。

我可以看到两种方法。第一个是将逻辑放在perform 块中。第二个是使用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 函数中吗?

【问题讨论】:

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


    【解决方案1】:
    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 提取为私有方法等,根据需要应用重构。

    为什么要使用around_perform?您在这里不需要工作实例。 根据您的需要,您还可以使用 https://github.com/mhenrixon/sidekiq-unique-jobs 之类的方式检查当前是否有任何作业待处理(抱歉,我对 ActiveJob API 不是很熟悉)

    【讨论】:

    • 我可以看到around_perform的用法使代码更易于阅读,因为我们可以将重新排队逻辑和执行分开。
    • 问题是关于最优雅的方式 :)
    猜你喜欢
    • 2011-06-01
    • 2015-02-18
    • 2017-12-02
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 2017-03-27
    相关资源
    最近更新 更多