Scheduling Tasks with Cron

30 November -0001
by: Justin
April 28, 2003
Ok, I'm going to assume you've read the article on BASH shell scripts or are familiar with shell scripting in general. Lets say you've created a great shell script that will back up your work, compress it, and move it somewhere else for storage. For instance, if you have a shell script like this:

#! /bin/sh
#
tar -cf /home/jkeane/backup.tar /var/www/html/mysite/*
gzip /home/jkeane/backup.tar


and you save this shell script as /home/jkeane/backup.sh, to schedule backup.sh to run every day at one minute after midnight you can use cron.

Cron is a daemon process (meaning it is constantly on and listening) that is used to schedule tasks. Every user has a 'crontab' which is a list of all the tasks they've scheduled. To edit your cron entries you simply have to type:

crontab -e


The '-e flag' is for edit. You may want to change your default editor from vi or emacs or whatever it is default set to, to something a little more friendly. Personally I like to use pico which is part of the pine package. To change your default editor you can type:

$ EDITOR=/usr/bin/pico


substituting the path to your editor for '/usr/bin/pico'. You then have to export this variable to make it globally available using:

$  export EDITOR


If you want to make this change permanently then just append the following line to your .bash_profile (found in your home directory):

EDITOR=/usr/bin/pico; export EDITOR;


Once you've got your editor set try editing your crontab using the 'crontab -e' command. You probably won't see anything in your crontab at first. To add items to your crontab you simply type them in line by line. Each line will be a separate cron command. The format for each line is:

minutes(0-59)  hours(0-23)  daysofmonth(0-31)  monthsofyear(0-11)  dayofweek(0-6)  user  job


Note that 0 is Sunday in the days of the week field. For instance:

1	24	*	*	*	jkeane	/home/jkeane/backup.sh


Will fire off the 'backup.sh' script in the '/home/jkeane/' directory as the user jkeane every first minute of the first hour of every day. The stars stand for every, the one is for the first minute, the 1 is for the first hour (1:01 AM). Note that you can schedule more than one option for each field. For instance, lets say we want to run this task every half hour of every hour every day of every month. We can use:

0,30	*	*	*	*	jkeane	/home/jkeane/backup.sh


The commas delimit multiple entries in the minutes field.

Once you've edited your crontab to your liking save the file. You can check your crontab using

$ crontab -l


The '-l' flag is used for list and it will list your crontab. Once your changes are saved they will begin taking effect immediately. Be aware though that you can't schedule tasks that require any user interaction (such as SSH which requires a password to be entered), those will just fail. Check 'man cron' and 'man crontab' for more information.