Thursday, March 20, 2008

Running a schedule task for a rails application

There are several ways described in ruby on rails wiki. But for our need, I took the simplest one - create a cron entry that executes RunnerScript.

At first create a static Model method. RunnerScript can only access model and run its class methods, it cannot access controllers. For example, we needed a script that periodically check for expired items and mark. So, I wrote a class method like follows -

def self.mark_expired_items()
update_query = "status = #{Constant::Item::STATUS_EXPIRED}"
# find expired items
update_conditions = "status = #{Constant::Item::STATUS_PUBLISHED}
AND created_at < '#{(-Constant::Item::EXPRITY_TIME).days.from_now.to_s(:db)}'
"
update_all(update_query, update_conditions)
end



Then create a cron entry that runs this periodically. For our purpose (we wanted to expire item 4 days after publishing)
0 * * * * <project_path>/script/runner Item.mark_expired_items

Thats it. This script checks every hour for expired items and mark all of those as expired

1 comment:

we4tech said...

nice i heard about script runner but never used it. thanks for showing up the example