Rails 3 - Delayed_Job

4

我正在学习如何在我的Rails 3 + Heroku应用程序中使用delayed_job。

目前我有以下代码,它可以在请求时发送电子邮件(非延迟作业),但它可以工作!

UserMailer.conversation_notification(record.commentable, participant, record, @comments).deliver

我将其更新为以下内容,开始使用delayed_job:

Delayed::Job.enqueue UserMailer.conversation_notification(record.commentable, participant, record, @comments).deliver

但是出现了这个错误:"ArgumentError(无法排队不响应perform的项目)"

我还尝试过:

UserMailer.delay.conversation_notification(record.commentable, participant, record, @comments)

但遇到了以下错误:

NoMethodError (undefined method `delay' for UserMailer:Class):

有没有延迟作业(delayed_job)的专家?谢谢


1
未来的谷歌程序员们,首先尝试重新启动您的服务器。 - brittohalloran
3个回答

6

根据文档 https://github.com/collectiveidea/delayed_job,您的第二种方法是正确的,它移除了.deliver方法:

UserMailer.delay.conversation_notification(record.commentable, participant, record, @comments)

如果你收到了一个未定义的方法 delay 的错误信息,那么你是否已经在Gemfile中加入了DelayedJob?
gem "delayed_job"

自从包含了delayed_job,它会将“delay”方法添加到所有内容中。

2

我在使用delay时有过好坏经历,而且我发现它很难调试。所以你并不孤单!但是当你让它工作起来时,它就是值得的。

我已经学会在调用delay之前保存我的对象。通常我会从after_save回调中触发我的任务。

作为一个实验,有一段时间我使用了不同的模式。我为每个作业创建一个作业对象。例如,我会调用

Delayed::Job.enqueue(PersonJob.new(@person.id))

在我项目的其他地方,我会创建工作对象。在Rails 2中,我把它们放在lib/中。如果你在Rails 3中这样做,你需要修改application.rb config.autoload_path。

class PersonJob < Struct.new(:person_id)
  def perform
    person = Person.find(person_id)
    #do work
  end
end


config.autoload_paths += Dir["#{config.root}/lib/**/"]

1

我刚刚查看了文档,实际上已经有一段时间没有使用delayed_job了...

任务是Ruby对象,具有名为perform的方法,因此您需要排队一个执行此操作的对象。

UserMailer.conversation_notification(record.commentable, participant, record, @comments).deliver

在其perform方法中。
或者,您可以使用send_later:
UserMailer.conversation_notification(record.commentable, participant, record, @comments).send_later(:deliver)

我尝试了 "UserMailer.conversation_notification(record.commentable, participant, record, @comments).delay.deliver" 但是出现了 "NoMethodError (undefined method `delay' for #Mail::Message:0x10560f0d0):"。 - AnApprentice
我认为上面引用的文档有误,对于Rails 3,请参见:https://github.com/collectiveidea/delayed_job。 - AnApprentice

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