Moving Beyond SSH: Cron Jobs

Published on Apr 2, 2009   //  Development
Off

Moving Beyond SSH

Last week, when we were talking about backups, I briefly mentions cron jobs. I would like to expand further upon cron jobs, as they can be very useful.

Cron jobs allow you to automatically run a script on a recurring schedule. Like we used them last week, they’re useful for script that will automatically backup your server. They’re also useful for performing repetitive tasks for you, saving you time and from having to remember to do them.

There are two ways we can setup a cron job. If you need a script to be run on a very simple schedule (hourly, daily, weekly or monthly), then we can just move our script to a special folder. For this method, there are four special folders that Linux creates. Any files in these folders will be executed on the schedule on which that folder is associated with. These folders are /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly and /etc/cron.monthly which correlate with the schedule of hourly, daily, weekly and monthly, respectively.

However, if you need to run your script on a more complicated schedule, you can also setup a cron job in a more manual manner. For this, we need to edit the /etc/crontab file. Each cron job should be on a separate line and have a syntax like this:

minute hour day month day-of-week user command

Here’s a break down of the values for these:

minute = 0-59
hour = 0-23 (0 is midnight)
day = 1-31
month = 1-12
day-of-week = 0-6 (sunday is 0)
user = The user this command should be run under
command = The command or file you want to be run

For each field, you may specify multiple values, separated by a comma. For every value except for user and command, an asterisks (*) may be used as a wildcard. This means that it will apply to every possible value. To further this, you can use a wildcard and a “step” to make it only apply to values divisible by a certain number. For example, */2 for the month field would be equivalent to 2,4,6,8,10,12.

So, at the point in time when all these conditions are met, the command will be run. Let’s look at an example for running a command every day at 4:32am.

32 4 * * * root /some/file

Then there we have it, a cron job. At some point in time, you’ll need to set up a cron job, and remember that you have two possible methods of doing so. Go forth and automate your repetitive (server-related) tasks!