Life Applied

Life Applied

Apr 27 / 11:56am

Using rake to send email asynchronously

For Boply I had been sending out the notification emails when the user confirmed their order. The issue with that of course is that it could be slow or it might never respond depending on the SMTP server. Given that I decided to queue the emails and send out later. To do that I did the following:

 

1. Create a model called EmailQueue (order_id, method_name).

This will store the orderId as well as the method name in the Notifier to call

2. On confirmation of the order put an entry into the email_queues table

3. Create a rake task to send the emails

    I added a new file in lib/tasks called mailer.rake with the following contents:

desc "Send any notification emails"

task :send_emails => :environment do

queuedEmails = EmailQueue.find(:all)

for qEmail in queuedEmails

order = Order.find(qEmail.order_id)

notification = Notifier.send(qEmail.method_name, order)

notification.deliver

qEmail.destroy

end

end

 

4. I am using slicehost so I createda file called runCron.sh which will be called from a cron job to run the rake task

 

#!/bin/bash

cd <root of your rails app>

rake RAILS_ENV=production send_emails

 

5. Finally I added to the crontab

crontab -e 

*/5 * * * * <path to shell script>/runCron.sh