How to run a rake task from cron
2010-04-21, Posted in Ruby, Programming | 我来说两句
Say you want to do run some stats on your Ruby on Rails application nightly. Create a rake task to do what you want then use cron to execute it.
1.Preflight information
First we need to create the RoR application.
rails cron cd cron script/generate model my_model vi config/database.yml (set the database username/password, and databases created in your environment)
2. Creating the rake task(s)
2.1 Simple task
First lets see how to call any ruby code from rake. Rake code is placed in lib/tasks/FILENAME.rake. So lets create a lib/tasks/cron.rake and place this code in it:
namespace :cron do desc "Just what Date is it really" task(:dummy ){ p Date::today.to_s } end
running rake -T cron gives us this:
rake -T cron (in /Users/linda/example/cron) rake cron:dummy # Just what Date is it really
now lets execute the the rake task
rake cron:dummy (in /Users/linda/example/cron) "2010-04-21"
Ok so that shows us how to call any kind of ruby code from rake. But what happens when you want to do something fancy and work with the database.
2.2 Model task
This is actually how I use the rake tasks the most. To do some expensive calculations on the database. For example lets say there is a model called MyModel which has a method called calc_stats. Add the following code to your model:
class MyModel < ActiveRecord::Base def self.calc_stats # Do something spiffy with the model here "Finished!" end end
So the additional rake code /lib/tasks/cron.rake would look like this:
desc "Example of calling a model" task(:calcstats => :environment){ p MyModel.calc_stats }
Did you notice the difference between the first task(:dummy) {} and now task(:calcstats ⇒ :environment){}. That is the magic to get the rails environment passed into your rake task.
running rake -T cron gives us this:
rake -T cron (in /Users/linda/example/cron) rake cron:dummy # Just what Date is it really rake cron:calcstats # Example of calling a model
Lets execute the rake task
rake RAILS_ENV=production cron:calcstats (in /Users/linda/example/cron) "Finished!"
3. Setting up the cron job
Simple rake tasks Command
cd /path/to/rails/app && /opt/csw/bin/rake cron:dummy
Rake tasks which need the rails environment Command
cd /path/to/rails/app && /opt/csw/bin/rake RAILS_ENV=production cron:calcstats
Note:This is for accelerators paths for Shared accelerators are different. Use which rake to find out the correct path to use for your system.