Search code examples
ruby-on-rails-3cronrake

Writing a rake task to send daily emails


I'm really new to rails. I'm trying to learn how to write a cron job with a rake task to send daily digest emails. How should I go about doing this?

I'm guessing that I write a loop in the task to go through each user and compile and email. Then I send it inside the for loop.

How do I set this rake task as a cron job so that it runs in the background? This seems like it should be super simple, but I feel like I'm missing something.


Solution

  • One way to do this, as you've visualized already, is to define a rake task which would run at a scheduled time. Crontab is best for that if you're on a Linux system. Following are the steps you would follow to do that:

    1. The rake task with the logic of fetching the emails to send digest emails.

    2. A shell script, digest.sh which would load up and run the rake task. Something like this:

    cd /your/app /usr/bin/rake utils:sendNotifications > /your/app/log/notifications.log

    We're telling it to go into your application folder ( /your/app ), run the rake task utils:sendNotifications and log the output in log/notifications.log

    1. And finally, schedule tasks on Linux using crontab.