Rails comes with a built-in tool for running tasks independent of the web cycle. The rails runner
command simply loads the default Rails environment and then executes some specified Ruby code.
Some of use cases :
- Data import
- Execute methods of your models.
- Sending batch emails
- Nightly report generation
Showing here some code example for
Let’s say you want to generate a nightly report and send it out to multiple users
1
|
|
This will execute send_me!
method for DailyReport
class.
rails runner
will give us access to all rails environment so we can even use the Active Record finder methods to extract data from our application.
1
|
|
Here we are just listing out emails of all users in our system.
1
|
|
Output will be
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
A sample crontab to run that script might look like
1
|
|
This script will run daily to send out daily report.
The Rails Runner is useful for short tasks that need to run infrequently.
But jobs that require more heavy work are best handled by other libraries.
I use rails runner
whenever I need to run a small task.
Reference links :
There are other better library available for handling background process. But here I wanted to talk about rails runner