Wednesday, December 10, 2008

Cron job on ROR without any third party gem and library

When you are working of a large project it is very much natural that you will need to run cron job. suppose you want to take a back up of your database on every day. or you have such a site that you have to include a recurring billing system for the members. So what you will do now ?? simple you will need a cron job to do these sort of tasks. there are couple of ways you can run cron job on ROR. but all the cases you have to use third party gems or other things. here I will show you a simple way to run cronjob. without any third party gem or library and using the linux's crontab command.


you have to make a new class which actually extend the active records base class. for an instance suppose we are going to create an invoice_generator class which actually make an invoice on the first day of every month.

Here I am making the invoice_generator.rb file under app/cron folder. you can create it some where else.

class invoice_generator < ActiveRecord::Base
invoice = Invoice.new
company = Company.find_by_id(1)
invoice << company.generate_invoice
invoice.save!


end


Note: Here I am showing only the invoice_generator.rb file not all other files. these line of code will generate the invoice for only one company.

now you can test the file from the command line by running the following command

ruby script/runner app/cron/invoice_generator.rb

now you can run the same command from the linux's crontab command
$ crontab -e

then type

* * 1 * * ruby script/runner -e production /root/sami/test/app/cron/invoice_generator.rb

Note: here my aplication folder is test and that is under /root/sami directory

1 comment:

Jitu said...

Nice post.
Helpful for many projects.