试图了解Rails中的delayed_job,我想更新我的图库中已过期的所有PIN
class UpdatePinJob < ApplicationJob
queue_as :default
def perform(gallery)
gallery.where('DATE(expired_pin) > ?', Date.today).update_all('pin = ?', 'new_pin_here')
end
end
这是使用该作业的正确方法吗?那么我该如何在我的 Controller 中调用它呢? 我希望我的问题是有道理的,为什么我在这种情况下使用队列,因为我在想如果我的画廊有数千个,并且我想更新所有内容,那是我在想使用delayed_job可能有助于扩展它:) 如果我的问题有问题,抱歉,我在这里试图理解
最佳答案
您走在正确的道路上。我建议按照此处的说明进行操作:ActiveJobsBasics
要在 Controller 中调用它,您应该这样做:
# Enqueue a job to be performed as soon as the queuing system is free.
UpdatePinJob.perform_later(gallery)
# Enqueue a job to be performed 1 week from now.
UpdatePinJob.set(wait: 1.week).perform_later(gallery)
您应该注意的一件重要的事情是实际执行该作业。根据 ActiveJob 的说法:
For enqueuing and executing jobs in production you need to set up a queuing backend, that is to say you need to decide for a 3rd-party queuing library that Rails should use. Rails itself only provides an in-process queuing system, which only keeps the jobs in RAM. If the process crashes or the machine is reset, then all outstanding jobs are lost with the default async backend. This may be fine for smaller apps or non-critical jobs, but most production apps will need to pick a persistent backend.
我会选择Sidekiq
不要忘记这样做:
# config/application.rb
module YourApp
class Application < Rails::Application
...
config.active_job.queue_adapter = :sidekiq
...
end
end
编辑:如果您对如何安排感兴趣,这取决于您使用的技术。 如果您使用 Heroku 进行部署,则可以使用 Heroku Scheduler 。如果您在 Digital Ocean 中部署,则可以使用 Cron Jobs。
关于ruby-on-rails - 任何示例如何通过 Rails 中的延迟作业进行批量更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61775462/