Rails: automatic tasks

Follow me
Follow me

Latest posts by Tomasz Antas (see all)

Jan 10, 2015

Many projects require to run maintenance tasks, which allow to make database backups or run custom scripts. Rails is supported by whenever gem cooperating with cron – time-based job scheduler in Unix systems.



Whenever gem allows to create a schedule for custom scripts in 3 easy steps. Firstly, we create and save custom task in lib/tasks directory. Secondly, we have to define when this custom task should to be run. We do this in schedule.rb file. Finally, we export scheduled task to cron - Unix tool which trigger automated tasks.



Add following line to Gemfile:

And run bundler:

In next step, use following command:

Above command should create all necessary files in rails project.


Create task

In example, we create a task which will delete all records older than today from database. Create delete_old_records.rake file in lib/tasks:


Schedule task

In config/schedule.rb file, we can define when the task should to be run. If we want to run task every night at 3:00, we have to do something like this:


Register task in cron

Our task has to be triggered by cron. So we have to export our task from Rails project to this Unix system tool (cron) by command:

Now, you can use following command to check that the task is registered properly in cron:

If you want to verify that your task is working correctly, you can also run rake task without cron:




Tomasz AntasRails: automatic tasks