2

When using Rails Action Mailer, you have the option to use deliver_now to send the email immediately, or deliver_later to send through asynchronously using Active Job. If Active Job is not specified an adapter, it will use an in-process thread pool which would not persist if the server were to stop. Alternatively, I can create a Job to manage my e-mails, which I can then call with perform_now or perform_later, which as I understand is more or less the exact same thing as deliver_now and deliver_later.

My question is, if I specify an adapter, let's say Sidekiq, and then have a database to store my jobs, why would I create a job to handle my e-mails? Is there any additional benefit, or is it an unnecessary step? On a slightly different note, if I did want to create a job for the process, would my email method need to have deliver_now or simply nothing at all? I presume if the e-mail were to say deliver_later, would it knock back the email to the end of the queue and force it wait again until it is sent?


To illustrate, if I have no Job set up to handle my emails, I could simply have:
class UserMailer < ActionMailer::Base
  def send_email(user)
    mail(to: user.email, subject: "My Subject")
  end
end

To call, I would use: UserMailer.send_email(my_user).deliver_later.

However, if I had wanted to add a job, and both options were called with UserJob.perform_later(user), would my setup be:

class UserJob < ActiveJob::Base
  def perform(user)
    UserMailer.send_email(user).deliver_now
  end
end

Or

def perform(user)
  UserMailer.send_email(user)
end

Lastly, I don't think this makes sense, but what would happen if I used:

def perform(user)
  UserMailer.send_email(user).deliver_later
end
michjo
  • 407
  • 2
  • 17
  • I use Sidekiq for asynchronous jobs. With Sidekiq you create special blocks called workers. You can call workers now, or later, or later in x.minutes or hours or whatever. If you deliver later, the job (worker) will be placed in a queue and processed when every preceding item placed in the queue has been processed. In a worker I deliver mail "now". – Maxence Sep 27 '18 at 13:37
  • I am not sure how active jobs work outside Sidekiq. I deliver later only the workers, not the emails. This thread may disambiguates your case : https://stackoverflow.com/questions/32619366/difference-between-action-job-mailers-deliver-now-and-deliver-later I recommend to only deliver now your emails and if an email needs be delivered later, just place it in a job. – Maxence Sep 27 '18 at 13:43
  • You've asked a few different questions there with various follow up questions. I think you're more likely to get better answers if you stick to one clear question. – Shadwell Sep 27 '18 at 13:50

0 Answers0