The debug messages you showed make perfect sense - the action of the mail program ends immediately, because the mail action itself is asynchronous and processed by the Delayed task in a completely different process. Thus, the mail program class itself does not know how the mailing ended.
Instead, I think you need to complete the deferred task hooks . You will have to rewrite your mail and calls to send emails, though.
I have not tested it completely, but something in the following lines should work:
class MailerJob def initialize(mailer_class, mailer_action, recipient, *params) @mailer_class = mailer_class @mailer_action = mailer_action @recipient = recipient @params = params end def perform @mailer_class.send(@mailer_action, @recipient, *@params) end def success(job) Rails.logger.debug "recording email!" @recipient.emails.create! end def failure(job) Rails.logger.debug "sending email to #{@recipient.email} failed!" end end
MailerJob is a custom job that must be run by a Delayed job. I tried to make this as general as possible, so it takes the class of the mail program, the action of the mail program, the recipient (usually the user) and other optional parameters. It also requires recipient have an emails association.
Two hooks are defined in the task: success upon successful completion of the mail action that creates an email record in the database, and the other for registration failure. Actual dispatch is performed in the perform method. Please note that the delayed method is not used inside it, since the entire task is already highlighted in the background. Queue delay for calls.
To send mail using this custom task, you must insert it in the specified task , for example:
Delayed::Job.enqueue MailerJob.new(UserMailer, :spam!, User.find(1))
Borama
source share