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

I’m mainly writing this post for my own reference, I’m assuming most people have heard of and their free tool certbot for creating and automating SSL certification requests and renewals. I used to use startssl’s free service but it was a lot of hassle.

In a recent project I have been using UUIDs as the primary key type with Rails 5 and PostgreSQL. This can be useful if your objects IDs are publicly exposed and you want to disguise the fact that they are a sequence, or how early on in the sequence they might be ;-)

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.