Scheduled Tasks in Rails with the Whenever Gem

I recently had a need to regularly pull information from a website other than my own into my Rails app. After poking around I found a few options, including a Rails Cast on a gem called Whenever that claimed to be able to easily perform tasks on a schedule.

In the end, Whenever worked for me. However, I’d say there is less information on it than some of other gems I’ve used, so this blog post is an effort to make clear for everyone else what I found confusing. I’ve created a demo GitHub project as an example. The project is very simple, it just adds a random number to the database every 2 minutes, and then prints how many random numbers there are to a text file every five minutes.

Installing Whenever is quite simple: “gem install whenever” works, though I put “gem ‘whenever’, :require => false” in my Gemfile. Then in your project directory, run the command “wheneverize .”. This will create a new file in the config directory called schedule.rb.

My scenario required a schedule task depending on some information in my database. Therefore I needed access to ActiveRecord, and I couldn’t find an example of someone else who did that like I needed to. In the end it wasn’t difficult I just couldn’t find information on what I needed to edit.

This is what the schedule.rb file looks like in the demo project:

This says to execute “generate” on the SpecialNumber model every 2 minutes and execute “log” on the SpecialNumber model every 5 minutes. It also says we’re working in the development environment, which is important for ActiveRecord.

This is my special_number model:

As you can see it is very simple. It just makes a new random number, saves it to the database, and then also logs to a text file in the root of your rails project.

After all that is done you need to run “whenever -i” in the root of your rails project. This will update your crontab file appropriately. If this isn’t working for you, in addition to “whenever -i”, try running “whenever –set environment=development”. I saw some people mentioning needing to run this command and I’m not sure if it affected anything when I ran it.

Hope that makes sense! The demo project is here.

Published by

Chris

This is my blog about life and things I find interesting.