Pure ruby CRON jobs on rails.

Installing
I found a post by “Loren Johnson” that had code that worked well for me:

rails test
sudo gem install daemons
cd test
ruby script/plugin install http://svn.kylemaxwell.com/rails_plugins/daemon_generator/trunk
ruby script/generate daemon tester

Using
First off, check out the (brief) Daemon Generator readme file.

Open up the file that was generated from the “generate” command above:
/lib/daemons/tester.rb
It’s short — take a look. This is where your custom stuff will added. More on that later.

Open up your /log/xyz.log file (development.log, production.log, etc) — it should have a message like this: This daemon is still runnig at Tue Oct 09 13:43:38 -0700 2007.

…That was inserted by a function stub created within tester.rb.

Change tester.rb to do something useful… As a simple example, I changed the line in tester.rb from:
ActiveRecord::Base.logger << “This daemon is still running at #{Time.now}.\n”
to:
ActiveRecord::Base.logger << “Disk space free: “+`df -hl | grep /dev/sda2`+”\n”

….. you get the idea.

NOTE that changing the code within the file tester.rb does not take effect until you restart the daemon: ruby script/daemons restart

Links
http://kylemaxwell.typepad.com/everystudent/2006/08/after_writing_r.html
http://wiki.rubyonrails.org/rails/pages/HowToRunBackgroundJobsInRails
http://douglasfshearer.com/blog/cron-jobs-in-ruby-on-rails

Advertisements