【问题标题】:Moving Mailer action to Resque queue将 Mailer 操作移动到 Resque 队列
【发布时间】:2018-09-05 21:19:44
【问题描述】:

控制器操作调用TextMailer.contact(fg, mailing).deliver_now,但是需要在确定的时间使用 resque-scheduler gem 将其移动到后台作业中。

因此控制器动作现在会调用:

 Resque.enqueue_at(@time, DelayedMailer, @fg.id, @mailing.id)

使用 Resque 设置了一个新的 rake 任务...

task "resque:setup" => :environment do
  Resque.schedule = YAML.load_file("#{Rails.root}/config/resque_schedule.yml")
  ENV['QUEUES'] = *
end

运行delayed_mailer 作业

class DelayedMailer
  @queue = :mail
    def self.perform(time, fg_id, mailing_id)
    fg = Fg.where('id = ?', fg_id).first
    mailing = Mailing.where('id = ?', mailing_id).first
    TextMailer.contact(fg, mailing).deliver_now
 end

有两个句法元素需要澄清。

1) perform 方法是否需要调用时间值(这似乎违反直觉,因为使用enqueue_at 调用 Resque 显式给出了一个时间键,这隐含地不需要重复)?

2) ActionMailer 方法是否可以在没有进一步更改的情况下被调用,就像它之前运行的那样,或者队列是否会以某种方式中断某些逻辑?

【问题讨论】:

  • 我建议您阅读有关 ActiveJob 的内容,您可以将 Resque 配置为后端,并且 ActionMailer 将支持自动使用 Resque 的异步交付方法。
  • 嗯,是的,我有。 rails 指南指出“您可以使用任意数量的参数定义 perform”......虽然resque-scheduler github 页面定义了 enqueue_at,但它没有说明是否需要在 perform 中调用原始的 at-time 调用(我假设不是因为作业已经存储在那个点“延迟队列存储在redis中并被持久化”)。

标签: ruby-on-rails resque-scheduler


【解决方案1】:

您可以配置 resque 以使用 ActionMailer。

  1. gem 'resque' 添加到您的gemfile。
  2. 更改application.rb - config.active_job.queue_adapter = :resque 中的适配器
  3. 使用以下命令生成作业 - rails g job SendEmail

class SendEmail< ActiveJob::Base
  queue_as :default

  def perform(fg_id, mailing_id)
    fg = Fg.where('id = ?', fg_id).first
    mailing = Mailing.where('id = ?', mailing_id).first
    TextMailer.contact(fg, mailing).deliver_now
  end
end

在你的控制器中,你可以这样做

SendEmail.set(wait: 10.seconds).perform_later(@fg.id, @mailing.id)

【讨论】:

  • 这有点离题了。正如问题所述,每封邮件都“在确定的时间”标记@time 实例变量。这就是为什么 enqueue_at 被调用的原因,根据 resque-scheduler gem。因而这两个问题。由于这是我第一次注意到对config.active_job.queue_adapter 的引用,请说明理由。现在我的队列是在没有这样添加的情况下生成的。
  • config.active_job.queue_adapter 用于设置queueing 后端。
  • 你为什么要设置@time,而工作是enqueued
  • enqueue_at。在 resque-scheduler gem 允许的情况下,它被安排在预定的时间。
  • 对于您的问题 #2,您不必对 ActionMailer 方法的逻辑进行任何更改。它将继续表现相同,只有调用会改变。
猜你喜欢
  • 1970-01-01
  • 2015-12-20
  • 2016-03-01
  • 2012-10-18
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
  • 2012-08-22
  • 2015-10-10
相关资源
最近更新 更多