Wednesday, 8 June 2011

Schedule tasks using cron

This is a fairly important objective, at least on the surface this is something that really helps you the system administrator. At any rate, I'll refrain from rambling even though I'm in a rambling mood.

Interestingly, Anacron is now used for running daily, weekly and monthly tasks. The key advantage that anacron has over cron is that you can limit the hours the jobs run at and you can also introduce a random delay, to, for instance prevent several servers running a task against a database server all at the same time.

The /etc/crontab file has a fairly good description of the time element of a task definition, alternatively you could have a look at the man pages. In general you can schedule a task by simply placing a script in the relevant cron folder, e.g. say you want to run script every hour, you just need to copy it to /etc/cron.hourly.

If you had a look at /etc/cron.hourly, you might have noticed a file called 0anacron, this file actually kicks off the anacron tasks.

The hourly, daily, weekly, etc might not be granular enough for you, in which case you can edit /etc/crontab or if the user's crontab file. The latter is done with the following command, which is simply vi for the user's crontab file.
crontab -e
A few points about the time elements. In the day of the week field 0 and 7 mean Sunday and if you specify day of the week and day of the month, it will run at both specified times. If you want a task to be repeated every x number of minutes, simply have the first time element set as */x,  e.g. to run as user myuser every 5 minutes, the following line would be needed (assuming that you are either logged in as myuser or that you have invoked : crontab -u myuser -e to access myuser's crontab file)
*/5 * * * *
You could also set intervals, e.g this will run every 5 minutes between 20 and 40 minutes past the hour
20-40/5 * * * *
If running the jobs from /etc/crontab then you do need to specify the user, normally root I would guess.

Note the following excerpt from the manual regarding permissions:
If cron.allow file exists, then you must be listed therein in order  to  be  allowed  to  use  this  command.   If  the cron.allow file does not exist but the cron.deny file does exist, then you must not be listed in the cron.deny file in order to use this command.  If neither of  these files  exists, only the super user will be allowed to use this command.
For completeness, a user can list their cron tasks using crontab -l and delete with crontab -r or you could just visit this link, which I only found when looking for info regarding cron.allow, blast.

Always check that the tasks are running as expected by checking the log (/var/log/cron).

No comments:

Post a Comment