Read more

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

Henning Koch
June 04, 2020Software engineer at makandra GmbH

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 ).

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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
Posted by Henning Koch to makandra dev (2020-06-04 12:34)