Friday, May 15, 2009

CRON: Schedule Automated Jobs

If you want to automate running any job, say running a BASH script, every day at 5:00 am - a solution in Linux/Unix is running a CRON job.

For example, you might want to back up your /home directory every day. In a linux system you can automate this very easily. It makes life so much easier - you do not have to remember to backup, even better - you don't even have to even move your finger. Let Linux take care of it for you!

To run a cron job:

1) Make sure you are running the crond daemon on your system.
eg: In a fedora system you might want to run
/etc/init.d/crond start

2) It is always better to run cron as user than as root. To setup a cron job as a user you need to create a text file specifying your job. There is a command to create this text file in linux - "crontab". Run crontab as a user.
crontab -e
This command should open a text file in your default text editor (usually "vi"). If you want to change your default text editor to, say emacs, type
export EDITOR=emacs
Then use crontab -e.
Now edit the file to add your cron job. Below is an example cron file I use:

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
HOME=/home/username
LOGNAME=username

# run-job
0 5 * * * bash /home/username/rsync_backup/rsync_bash_script.sh > /home/username/rsync_backup/backup.log


Now save the file and restart your crond by using /etc/init.d/crond restart

The above job is to run the script rsync_bash_script.sh and store the output of the script to backup.log file. I have only one job here, but you can add any number of lines/jobs to the above file.

The 5 fields "0 5 * * *" before each line are required to tell cron when to execute the command.
In this example I execute the command at:

0 - at 0th minute of the hour
5 - at the 5th hour of the day(i.e 5:00 am)
* - every day of the week
* - every week of the month
* - every month of the year

3) Finally you want to make sure you are not black listed from using cron as a user in the current system. To make sure of that you need to check /etc/cron.allow and /etc/cron.deny files.

Make sure your username does not appear in the /etc/cron.deny file. If both files are empty you are fine.


You are now setup to run a routine bash script every day at 5:00 am.

No comments: