Friday, June 1, 2012

Something about Cron

(info valid on CentOS 5)
Cron is a daemon that executes commands/scripts automatically at a scheduled time. Cron is installed on most linux distributions by default and placed in the start-up scripts (On OS X, the preferred command is launchd). To check if cron is running try:

ps aux | grep crond

Cron jobs can be created by placing a script file in /etc/cron.* directories.

ls -l /etc | grep cron

lists the hourly, daily and all other directories.

We prefer the crontab either for simpler commands or if we want more flexibility with the scheduling. Otherwise placing the script in either of the /etc/cron.* directory works just fine.


An entry in the crontab file consists of 7 parts, each separated by a single space:

min   hour    day-of-month month day-of-week user command
0-59  0-23        0-31      0-12    0-6                 


 These directories are setup via the /etc/crontab file as shown by reading /etc/crontab file:


SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# run-parts
01 * * * * root run-parts /etc/cron.hourly
#executes 'run-parts /etc/cron.hourly' as root at 01 minutes of every hour, every day, every month, every day of month.
02 4 * * * root run-parts /etc/cron.daily
 #executes 'run-pars /etc/cron.hourly' as root at 04:02, every day, every month, every day of month.
22 4 * * 0 root run-parts /etc/cron.weekly
#executes 'run-parts /etc/cron.hourly' as root at 04:22, every month, every sunday (0=sunday).
42 4 1 * * root run-parts /etc/cron.monthly

#executes 'run-pars /etc/cron.hourly' as root at 04:42, 1st of every month, irrespective of the day of month.

Placing a script in /etc/cron.daily will execute the script at time as shown above.
Now, we could use the crontab -e command to edit our crontab file and add a line in it. This gives us a finer grained control over scheduling of our job. For example if we want to run our script every half hour we could add a line such as:

*/30 * * * * * username /path/to/my/script.sh  #(*/30 = any min that is divisible by 30 i.e.30 and 60)

every 3 hours:

00 */3 * * * username /path/to/my/script.sh

every 3 days at midnight:

 00 00 */3 * * username /path/to/my/script.sh

every 2 hours between 1000hrs and 1600hrs

00 10-16/2 * * * username /path/to/my/script

No comments:

Post a Comment