我有一个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
答案 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)
success
列ContactEmail - 首先将其保存为false
,然后将作业更新为true