Last time we were talking about task management in GNU/Linux. Now is the time to learn how to plan tasks. It is performed using the ingenious Unix daemon called cron.
Cron itself is nothing more than a software daemon set to automatically run a certain command or process at a certain time. It is therefore used to plan tasks, mostly repeated ones (we will have a look at one-time tasks next time, when describing the at tool).
This means we can periodically perform a certain pre-defined task – for example, cron is often used for regular backups during night-time hours, automated restarts of certain services (or entire systems) at pre-defined times, or scheduled launch of batch tasks as a part of mass data processing.
The tasks are launched using the definition in the crontab file, a.k.a. /etc/crontab. There are tools for easier editing that automatically launch a text editor, meaning you can just run the crontab command and begin right away.
Individual commands are listed in rows, with the time being the first item, followed by the task subject itself. A typical example:
15 0 * * * uzivatel /usr/bin/updatestats
This command will execute the program /usr/bin/updatestats exactly 15 minutes past midnight every day under the specified user (uzivatel).
The syntax is as follows:
1. Minute (0–59)
2. Hour (0–23)
3. Day of the month (1–31)
4. Month (1–12)
5. Day of the week (0 = Sunday, 1 = Monday, …, 6 = Saturday)
Each of these fields can also contain an asterisk, which means that the value is disregarded, i.e., the command is always executed (e.g., an asterisk in place of the hour item means that the command is to be executed every hour).
The field can also contain a specific number (5), a list of comma-separated numbers (15,30,45), a range with a dash (1–10) and even some more complex syntaxes in certain implementations of Cron (such as a slash for multiplications, meaning */5 can mean “every five minutes”).
Another interesting bit is the option to edit the user cron, i.e., settings of tasks that will be launched via personal, user-bound cron as opposed to the main one. This is performed using the crontab –e entry.
In this case, everything is basically the same. The only difference is that the user is no longer specified during the task input (the tasks will be executed under the account of the user that has used the crontab -e entry). This way, we can also edit task lists of other users from the “root” by adding the -u user switch, for example, crontab -e -u pepa. Even in this case, the user is not specified when entering individual tasks as everything will be executed under the user “pepa”:
15 0 * * * /usr/bin/updatestats
Cron is a very powerful and useful tool that you will surely come to appreciate. In the following part, we will be looking at one-time action planning using the at tool.
Author: Jirka Dvořák