Cron is great for handling recurring tasks, but it is an external dependency with a crazy syntax. There are multiple gems that helps us to add a cron job.
But I supposed and think whenever gem is the best to use, if you want a cron job running for yours system.
Requirement
- Ruby
- Rails/Sinatra as framework
- whenever gem
Setup steps
- Add whenever gem to your Gemfile
gem 'whenever', :require => false
- Then do bundle install
- When bundle install is completed then just initialize the cron-tab
bundle exec wheneverize.
#Output look like this [add] writing './config/schedule.rb' [done] wheneverized!
This will create an initial config/schedule.rb
file for you.
- Now go and edit your schedule.rb
every :friday, :at => '4am' do runner "MyModel.some_process" rake "my:rake:task" command "/usr/bin/my_great_command" end
runner: This will act similar to rails console. What ever ruby code you want to execute just put here inside double quot.
rake: This will run a rake command inside double quot.
command: This will execute unix commands inside double quot.
- Now move your cron to crontab
bundle exec whenever --update-crontab APPNAME
# Output look like this # Begin Whenever generated tasks for: APPNAME 0 4 * * fri /usr/bin/my_great_command 0 4 * * fri /Users/eifion/rails/cmthakur/app/script/runner -e production "MyModel.some_process" @reboot cd /Users/eifion/rails/cmthakur/app && RAILS_ENV=production /usr/bin/env rake my:rake:task # End Whenever generated tasks for: APPNAME
- See whether your crontab updated or not
crontab -l
- Now to get work in production add following to your deploy.rb file
set :whenever_command, 'bundle exec whenever' require 'whenever/capistrano'
after "deploy:symlink", "deploy:update_crontab" namespace :deploy do dec 'Update cron tab' task :update_crontab, :roles => :app do run "cd #{app_path} && bundle exec whenever --update-crontab#{application}" end end
This is all about how a cron job is setup for your ENV.