Setting variables on the fly

brande edited this page Jun 11, 2012 · 11 revisions

If you wish to override variables in your schedule.rb file at runtime you can do so using the --set option. This is especially useful for changing your environment when deploying to a staging server or something similar.

Example:

whenever --set environment=staging

You can set more than one variable by forming a query string. Make sure to use quotes.

whenever --set 'environment=staging&cron_log=/my/other/log.txt'

A couple of notes:

  • Be aware of escaping and/or quoting when using --set with multiple key/value pairs (in other words, be careful with the “&”).
  • Use --set cron_log=PATH from the command-line to override any set :output, PATH calls in your schedule.rb (--set output=PATH DOES NOT work).

So you can define different tasks per environment:

case @environment
when 'production'
  every 1.day, :at => "#{Time.parse('12:00 A').getlocal.strftime("%H:%M")}" do
    runner "Company.send_later(:create_daily_stories!)"
  end 
when 'staging'
  every 15.minutes do
    command "thinking_sphinx_searchd  reindex"
  end
end

In some situations, you must set the environment with a separate bash command, as seen in this cap task:


  desc "Update the crontab file"
  task :update_crontab, :roles => :db do
    run "cd #{release_path}; whenever --set environment=staging; whenever --update-crontab #{application}"
  end

Sorry, the upper example does not work for me. The RAILS_ENV settings inside the cronjob was alway “production”… It seems that capistrano handle your exampe as two whenever calls where the second one does not know anything about the settings you did in the first whenever call …


just my two cents ;-)

If I change line:
run "cd #{release_path}; whenever --set environment=staging; whenever --update-crontab #{application}"

to:
run "cd #{release_path}; whenever --set environment=#{rails_env} --update-crontab #{application}_#{rails_env}"

it works perfect. ( _#{rails_env} at the end is not necessary but it helps during debugging...

Example recipe for webistrano:

Name, Description: What ever you like...
Body:
namespace :deploy do
     task :update_crontab, :roles => :worker do
           run "cd #{release_path}; whenever --set environment=#{rails_env} --update-crontab #{application}_#{rails_env}"
     end
end
after 'deploy:symlink', 'deploy:update_crontab'


cheers, 
    Brande