Run a Rails Rake Task with Cron
To run a Rails rake task from cron, cd into the app, set RAILS_ENV, and call the task with bundle exec. Because Rails needs its full environment, either use absolute paths and a login shell or let the whenever gem generate the crontab.
The crontab line
0 1 * * * cd /var/www/app && RAILS_ENV=production /usr/local/bin/bundle exec rake reports:nightly >> log/cron.log 2>&1 runs at 1 AM.
Load the environment
cron has no rbenv/rvm setup. Use the full path to bundle (find it with which bundle), or source your version manager at the top of the script. Always set RAILS_ENV explicitly.
Use the whenever gem
whenever lets you write schedules in Ruby (config/schedule.rb) and runs whenever --update-crontab to generate the correct crontab lines, handling paths and environment for you.
FAQ
How do I run a rake task from cron?
cd into the app and run RAILS_ENV=production bundle exec rake task:name with absolute paths, e.g. 0 1 * * * cd /app && RAILS_ENV=production /usr/local/bin/bundle exec rake reports:nightly.
Why does my rake cron job fail with bundler errors?
cron lacks your rbenv/rvm environment. Use the full path to bundle (which bundle) or source your version manager, and always set RAILS_ENV.
What is the whenever gem?
A Ruby gem that lets you define schedules in config/schedule.rb and generates the crontab with whenever --update-crontab, handling paths and env for you.