Manage cron jobs with whenever and capistrano

9379e0f68d34f1973b728c1b069135b2?s=106 Published on by Rails and Server

Keeping track of your apps scheduled tasks is usually a bit of a pain. It can be handled outside of your normal code processes such as github and missed in your code reviews.

However if you happen to be self hosting a rails application and using capistrano for deployments there is a handy gem to help you out, it’s called whenever.

Whenever provides a DSL for configuring cron jobs and integrates nicely with capistrano. A simple schedule to run a rake task every hour looks like this:

# config/schedule.rb
every 1.hour do
  rake "articles:fetch_comments_count"

To see how this translates into cron run bundle exec whenever, this just outputs the text it would insert into cron. If you want to export the schedule to cron you can run:

$ bundle exec whenever --update-crontab -i myapp_identifier

Capistrano 3 integration

If you’re using capistrano you don’t even need to run whenever --update-crontab on your server, why not have capistrano do it for you...

# Require this in your Capfile
require 'whenever/capistrano'

# Set the whenever identifier in your config/deploy.rb
set :whenever_identifier, ->{ "myapp_#{fetch(:stage)}" }

That’s it, simple! Capistrano will now keep track of your schedule and update your cron tab with each deploy. You’ll also have your applications scheduled tasks in your source code repository and they can be code reviewed along with your other changes.

What about heroku?

For heroku applications I try to keep a list of rake tasks in the readme file and remember to add them into the heroku scheduler when deploying. I’m on the lookout for a better way to handle this, if you have any ideas please post them in the comments!

Related Articles

As we’re always seeking to keep our code as clean and efficient as possible we wanted try out PostGIS, an addon for the open source PostgreSQL database we use on almost every app we’ve built.

Thoughtbots clearance gem is an alternative to the more popular Devise gem that allows you to easily add authentication to a Rails app.

A little known Rails feature is built-in JST support and we can leverage this along with EJS to have a neat and tidy JS templating solution.