Posted about 1 month ago. Visible to the public.

whenever: Installing cron jobs only for a given Rails environment or Capistrano stage

We use the whenever gem to automatically update the crontab of the servers we deploy to. By default, whenever will update all servers with a matching role (we use the :cron role ).

This card describes how to install some tasks only for a given Rails environment or for a given Capistrano stage.

Installing jobs only for a given Rails environment

In your schedule.rb you may use environment variable to access the Rails environment of the current deployment:

Copy
if environment == 'staging' every :day do # Setup job that will only run for Rails environment "staging" end end

You may test the cron output like this (no changes will be made to your crontab):

Copy
bundle exec whenever --set environment=staging bundle exec whenever --set environment=production

Installing jobs only for a given Capistrano stage

In some apps we have custom capistrano stages like this:

Copy
customer1-staging customer1-production customer2-staging customer2-production

Installing a job for only some of these stages requires a little more code.

First, in our deploy.rb we extend the default environment variables for the whenever command. The following will make the capistrano stage available as an environment variable named STAGE:

Copy
set :whenever_command_environment_variables, ->{ fetch(:default_env).merge(rails_env: fetch(:whenever_environment), stage: fetch(:stage)) }

You may now access ENV['STAGE'] in your schedule.rb:

Copy
if ENV['STAGE'] == 'customer1-staging' every :day do # Setup task that will only run for Capistrano stage "customer1-staging" end end

You may test the cron output like this (no changes will be made to your crontab):

Copy
STAGE=customer1-staging bundle exec whenever STAGE=customer2-staging bundle exec whenever

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Henning Koch
Last edit:
about 1 month ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more