ruby-on-rails - 任何示例如何通过 Rails 中的延迟作业进行批量更新

标签 ruby-on-rails ruby activerecord delayed-job

试图了解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/

相关文章:

ruby-on-rails - Rails - 使用 [ 和 ] 从字符串中提取子字符串

ruby - 如何只获取没有命名空间的类名

ruby - 如果仅输入零,则从字符串中删除多个零

ruby-on-rails - activerecord-2.3.14 与 ruby​​ 1.9.2::undefined 方法 `reject' 中断 "4":String

ruby-on-rails - 计算不包括周末的天数

ruby-on-rails - 如何以递归方式将 YAML 文件扁平化为 JSON 对象,其中键是点分隔的字符串?

ruby-on-rails - 通过自继承STI模型获得关联

ruby - 点运算符与范围解析运算符与 Ruby 中的模块

ruby-on-rails - 根据 child 的创建日期对对象进行排序

ruby-on-rails - 如何在 Rails 中的对象上构建子关联而不保存父对象?