whenever: Installing cron jobs only for a given Rails environment or Capistrano stage
We use the
whenever
Show archive.org snapshot
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 ("deployment target").
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:
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):
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:
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
Show archive.org snapshot
for the whenever command
. The following will make the capistrano stage available as an environment variable named STAGE
:
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
:
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):
STAGE=customer1-staging bundle exec whenever
STAGE=customer2-staging bundle exec whenever