Sep 30, 2007

Cron job to run programs on a schedule

I was planning to run some scripts on daily basis to perform some cleanup jobs in database. Keeping that intention in mind, I reviewed cron scheduler.

cron is a Linux system process that will execute a program at a preset time. To use cron, I have to prepare a text file that describes the program that I want to execute and the schedule for them. Then I have to use crontab program to load the text file that describes the cron jobs into cron process.

The scheduler format of a cron job is -

[min] [hour] [day of month] [month] [day of week] [program to be run]


I created the cron rule text file (number.cron, describes how often the shell script will run) and set the rules to execute another program in every minute (a small shell script, print-number.run). See below -

#file: number.cron
* * * * * /home/shawon/cron-test/print-number.run

Note: To execute a command/script, the full path should be provided

I wrote the sample program to test the cron -

#file: print-number.run
seq 1 100 > /tmp/cron-test.log
sleep 10
rm /tmp/cron-test.log

To load my cron.number I issued-
#crontab number.cron
#crontab -l
* * * * * /home/shawon/cron-test/print-number.run

Now I watched /tmp/cron-test.log where log file should be created and deleted after 10 sec. Cron was doing good as expected.


To see the cron activities -
# tail -f /var/log/cron

To see whether cron was runnig (being root user) -
$ ps aux | grep crond

To run cron (if not running) -
$ crond

To see the list currently loaded in crontab -
#crontab -l


To add/edit the current crontab I used -
# export EDITOR=vi

#crontab -e

One helpful link related to cron scheduler-

http://www.scrounge.org/linux/cron.html

No comments: