Joyent

Translations of this page:

How to run a rake task from cron

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.

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)

Creating the rake task(s)

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)
"2007-09-23"

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.

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!"

Setting up the cron job

To create the cron job from webmin webmin→System→Schedule Cron Jobs→Create a new cron job

  • Execute cron job as: root
  • Command: (See below for the proper format)
  • Then set the appropriate schedule for the task

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

This is for accelerators paths for Shared accelerators are different. Use which rake to find out the correct path to use for your system.

 
accelerators/kb/rails/cron.txt · Last modified: 2008/03/20 22:50 by jashugan
 
Recent changes RSS feed Creative Commons License Driven by DokuWiki