In my app, when a user signs up, they are sent a confirmation email. I use delayed_job, to make the process of sending email go in background.
But disadvantage of using delayed_job is having a worker all the time. And having a worker for this is expensive.
Is there something other than delayed_job, that will make email sending go in background.
Here is my controller code snippet.
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
UserMailer.delay.registration_confirmation(@user)
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.js
The point is I am having 20-40 signups in a day. That means at most the the queue is busy for about 60 seconds and I will have to pay for the the entire day, which is very impractical. Some other nice approach.
I recommend setting up a cron that will run once every hour and send out e-mails. You’ll have to create a new model,
QueuedEmailor something similar, and then instead of using ActionMailer right away, save it as aQueuedEmail. This is basically the same thing that delayed_job does, but you’ll have more control over when it gets run, and crons don’t take up much memory.The cron should be to script/rails runner, and you should have a method in your
QueuedEmailmodel that will send out all pending e-mails. I recommend whenever to generate crontabs (quick to setup and very easy to use). The cron will look something like this (this example is set to run once a day at 2am, you can look up how to adjust the intervals, I don’t know off the top of my head):Or in Whenever:
QueuedEmail#send_pending
UserController#create
User#delay_email
None of this code is tested and is probably quite broken, but it’s the general idea that matters. You could also go one step further and extend the Rails ActionMailer, but that is far more advanced.