Using crons is one of the most important parts of being a system administrator. Sometimes its nice to turn your computer into an alarm clock by automatically switching on the news, but other times it's nice to run a 'garbage collector' on your files once a day. Here I will go over the basics of setting up cron jobs.
Accessing the cron configuration on unix systems can be done at any time by entering the following command:
crontab -e
If this is your first time to run this command, you will quite likely recieve a message asking you what editor you wan to use. The first option is 'nano' and the second is going to be vi or vim.tiny as shown below. If your new to editors, I highly suggest you use nano as it recommends.
A screen will load looking similar to this:
As you can see, I have added a line with a bunch of '*' characters. These represent time intervals to run. If you enter a *, that means to act on every unit of time. You can place integer values in here. Below is a diagram of what units of time they represent.
A nice 'trick' that is easier to read is to use @ symbols instead which act like shortcuts. The following are allowed:
- @yearly (or @annually) - new years (1st january midnight)
- @monthly - midnight on the first of the month
- @weekly - Sunday midnight
- @daily - acts at midnight
- @hourly - acts on the hour
- @reboot - acts on startup
Caution:
If all your services are scheduled to run at exactly the same time, your server load is quite likely to shoot up for a very short period of time, which can cause delays/issues. It is nice to spread-out your tasks, so if you want to run something once an hour, use
0 * * * *
and then:
1 * * * *
and so on.
Next to specifying the time, you need to specify the command, which contains the full path to the file you want to run. This may cause issues if your scripts are expecting to be called from the same directory that they are in (relative paths).
As a rule of thumb, it is best to specify the full path to the program that needs to run. For example don't put: "php /path/to/my-command.php" but "/usr/bin/php /path/to/my-command.php". If you are unsure what is the path to the program to execute, just enter "which (your-program-here)" into a shell and it should output the full path as seen below:
Finally, you need to specify what to do with the output. If you want to ignore all output and errors, simply append the following text to the end of the command:
> /dev/null 2>&1
However, if you do want to append everything to a file then use:
>> /full/path/to/log/file.txt
To only store the result of the last execution (not appending, but overwriting), its subtly different:
> /full/path/to/log/file.txt
The end result is that you should have a line of text similar to this:
* * * * * /usr/bin/php /full/path/to/script.php > /dev/null 2>&1
Each task that needs to be scheduled to run needs to be placed on its own line.
References
No comments:
Post a Comment