使用 Whenever gem with Rails Active Job 来安排批处理电子邮件作业

Using Whenever gem with Rails Active Job to schedule a batch email job

我正在尝试了解如何正确使用它,或者我是否将它用于正确的事情。我创建了一份工作:

  class ScheduleSendNotificationsJob < ActiveJob::Base
  queue_as :notification_emails

  def perform(*args)
      user_ids = User.
                joins(:receipts).
                where(receipts: {is_read: false}).
                select('DISTINCT users.id').
                map(&:id)

      user_ids.each do |user_id|
          SendNotificationsJob.create(id: user_id)
          Rails.logger.info "Scheduled a job to send notifications to user #{user_id}"
        end  
    end
   end

我想每天在规定的时间执行这项工作。工作轮询以查看是否有任何未完成的通知,将它们分批处理,然后将它们发送给用户,以便用户可以收到一封包含一堆通知的电子邮件,而不是一堆电子邮件,每封电子邮件有一个通知。我尝试使用延迟作业来执行此操作,但它似乎并非旨在定期安排某些内容。所以现在我正在尝试使用 whenever gem 来完成它,但我似乎无法弄清楚如何正确设置它。

这是我的 config/schedule.rb 文件中的内容:

every 1.minute do
   runner ScheduleSendNotifications.create
end

当我 运行 每当 -i 在控制台中时,我得到以下信息:

Lorenzs-MacBook-Pro:Heartbeat-pods lorenzsell$ whenever -i
config/schedule.rb:13:in `block in initialize': uninitialized constant Whenever::JobList::ScheduleSendNotifications (NameError)

我在这里做错了什么?我应该使用其他东西吗?我只是在学习 ruby 和 rails 所以非常感谢任何帮助。谢谢。

whenever gem 将字符串作为 运行ner 函数的参数。 Whenever 并不实际加载 Rails 环境,因此它不知道您的 ScheduleSendNotifications class。

下面的代码应该让 crontab 正确设置为 运行 你的工作。

every 1.minute do
  runner "ScheduleSendNotifications.create"
end

从您的项目目录 运行 whenever -w 设置 crontab 文件。 运行 crontab -l查看写入的crontab文件。系统每分钟都会执行你的 Rails 运行ner。如果出现问题,您可能需要从那里调试 ScheduleSendNotifications.create 代码。