当使用Delayed::Job时,如何使用ActiveJob设置优先级

9
当使用ActiveJob来排队作业时,如何设置延迟作业的优先级?
class GuestsCleanupJob < ApplicationJob
  queue_as :high_priority

  def perform(*guests)
    # Do something later
  end
end
4个回答

15

我花了一些时间,但我在Delayed::Job文档中找到了这种方法:

Delayed::Worker.queue_attributes = {
  default:       { priority: 11 },
  high_priority: { priority: 1 },
  low_priority:  { priority: 75 }
}
我已将此添加到我的初始化程序中,只是想分享一下,以防其他人也遇到类似情况!

4

定义一个定义优先级的实例方法是有效的,但是它不允许我重载值。 考虑以下这个类。

class GuestsCleanupJob < ApplicationJob
  queue_as :high_priority

  def priority
    1
  end

  def perform(*guests)
    # Do something later
  end
end

如果我执行

GuestsCleanupJob.set(priority: 55).perform_later(user, lead) # priority set to 1 not 55

它将以优先级1排队一个作业,并忽略我传递的55。

对于我的用例来说,这不提供足够的控制,所以我改为:

class GuestsCleanupJob < ApplicationJob
  queue_as :high_priority

  def default_priority
    1
  end

  def priority
    @priority || default_priority
  end

  def perform(*guests)
    # Do something later
  end
end

使用上述代码,默认情况下优先级将被设置为1,但我可以使用自己的。

GuestsCleanupJob.set(priority: 55).perform_later(user, lead) # priority set to 55

或者,您可以使用文档中指定的“set”来指定队列。MyJob.set(queue: :another_queue).perform_later(record) https://guides.rubyonrails.org/active_job_basics.html - aoh

3
使用 Delayed::Worker.queue_attributes 的解决方案看起来不错并且有文档记录,但它对我没有用......无论在 queue_attributes 中设置了什么队列优先级,所有作业的 priority 都为 0。 对我而言,以下方法能够解决问题:
class GuestsCleanupJob < ApplicationJob
  queue_as :high_priority

  def priority
    1
  end

  def perform(*guests)
    # Do something later
  end
end

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接