只有在delayed_job成功完成后才能保存对象?

时间:2010-09-17 06:02:09

标签: ruby-on-rails delayed-job

我有一个delayed_job,旨在使用邮件发送电子邮件。

完成后,我需要记录电子邮件已发送 - 我这样做是通过保存新创建的ContactEmail来实现的。

现在,即使delayed_job失败,新的ContactEmail记录也会被保存。

如何更正,以便只在邮件成功发送后保存新的ContactEmail?

以下是来自cron任务的片段,它调用delayed_job:

    puts contact_email.subject

    contact_email.date_sent = Date.today
    contact_email.date_created = Date.today

    contact_email.body = email.substituted_message(contact, contact.colleagues)

    contact_email.status = "sent" 

    #Delayed::Job.enqueue OutboundMailer.deliver_campaign_email(contact,contact_email)
    Delayed::Job.enqueue SomeMailJob.new(contact,contact_email)

    contact_email.save #now save the record

这是some_mail_job.rb

class SomeMailJob < Struct.new(:contact, :contact_email) 
   def perform
     OutboundMailer.deliver_campaign_email(contact,contact_email)
   end
 end

这是outbound_mailer:

class OutboundMailer < Postage::Mailer 

  def campaign_email(contact,email)
    subject    email.subject
    recipients contact.email
    from       '<me@me.com>'
    sent_on    Date.today

    body       :email => email
  end

2 个答案:

答案 0 :(得分:0)

您可以更新作业本身的状态。

例如:

contact_email.status = 'queued'
contact_email.save
contact_email.delay.deliver_campaign_email

然后在你的ContactEmail课程中,

会产生影响
def deliver_campaign_email
  OutboundMailer.deliver_campaign_email(self.contact, self)
  self.status = 'sent'    # or handle failure and set it appropriately
  self.save
end

delayed_job有一些神奇的位,它会添加到你的模型中来处理持久性。

为了处理你的OutboundMailer抛出异常,你可以这样做:

def deliver_campaign_email
  begin
    OutboundMailer.deliver_campaign_email(self.contact, self)
    self.status = 'sent'
  rescue
    self.status = 'failed' # or better yet grab the the message from the exception
  end
  self.save
end

答案 1 :(得分:-1)

  1. 您需要同步传送,因此在这种情况下请停止使用延迟作业并执行标准邮件传送。
  2. 或向您添加success列ContactEmail - 首先将其保存为false,然后将作业更新为true