Rails crontab with “whenever” gem
Posted March 27, 2010on:
gem “whenever“ provides you with the valid cronjob syntax and also writes / updates the crontab file for you.
1. Install the gem
gem install whenever
2. Add below line to your config/environment.rb
config.gem ‘whenever’, :lib=>false, :source=>’http://gemcutter.org’
3. Go to your application root directory and run the below command
This will create a “config/schedule.rb” file for you. EXAMPLE “config/schedule.rb” set :environment, :development set :path, "/var/www/MyApp" # Scheduled Hourly every 4.hours do command "/usr/bin/your_command" end # Scheduled Daily every 1.day, :at => '12:00 am' do runner "MyModel.yourmethod" end # Scheduled Weekly every :monday, :at => '11:00 pm' do rake "your:rake:task" end
Consider the above as the contents of your config/schedule.rb file.
4. Now from application root directory, run the below command
The above command will output valid syntax for the crontab as below.
0 0 * * * /var/www/MyApp/script/runner -e development “Model.your_method” 0 0,4,8,12,16,20 * * * /usr/bin/your_command 0 23 * * 1 cd /var/www/MyApp && RAILS_ENV=development /usr/bin/env rake your:rake_task
5. Now, To write the above content in your Crontab file run the below command.
you can see the above entries in your crontab file by running “crontab -e”.
That’s it, you are ready to go.