← Back to all snippets

How to run whenever cron jobs for a specific environment

David Anderson | May 15, 2019

When you only want to run whenever gem cron tasks for a specific environment.

Add a production_cron and a staging_cron to your config/deploy files and set the whenever_roles variable in `config/deploy.rb’

#config/deploy/production.rb
server 'deploy@123.123.1.1', user: 'deploy', roles: %w{web app db production_cron}

#config/deploy/staging.rb
server 'deploy@321.321.1.1', user: 'deploy', roles: %w{web app db staging_cron}

#config/deploy.rb
set :whenever_roles, -> { "#{fetch(:stage)}_cron" }
set :whenever_environment, -> { fetch(:stage) }
set :whenever_identifier, -> { "#{fetch(:application)}_#{fetch(:stage)}" }

Now add roles: [] to your task definitions.

  every 1.minutes, roles: [:production_cron] do
    rake 'notifications:process'
  end
  every 1.day, at: ['2:00 am'], roles: [:production_cron, :staging_cron] do
    rake 'db:backups:capture'
  end

Reference:

SUBSCRIBE

Drop your email in the box below to subscribe to my newsletter. Once per week you'll get Ruby/Rails tips, guides, job postings, and general thoughts from the web developer trenches.