Lesson 10 | The crontab command |
Objective | Explain the use of the crontab command to schedule a process. |
crontab command
Configuring cron
The proper way to run cron
is to configure the /etc/rc or
/etc/rc.local file to run it. A typical rc.local entry would be /usr/sbin/crond. Therefore, you do not use cron
as you would a
standard application. For example, you do not type cron filename
. You simply set it to run as a daemon.
crontab
After you have set crond
to run, the next step is to place scripts that contain entries you want to execute into the spool
directory. You refer to the cron program as follows: /var/spool/cron. You can place a file into the /var/spool/cron directory; however, you do not
run the file directly. To register the proper entries, you must use the crontab
command. The crontab program allows you to
create and manage the entries that inform the cron
daemon about the applications and processes you want to automate.
Using crontab arguments
The crontab
command allows you to create a crontab file, which you can then add to your crontab directory. The syntax for
using crontab
is
crontab arguments file
The arguments for crontab
are as follows:
-l
displays crontab
output as standard output
-r
deletes a current crontab
entry
-e
edits a current crontab
entry
Linux also adds a –u
option, which specifies the user's crontab
file. For example:
crontab –u root –l
would list all crontab
entries belonging to root. On other versions of UNIX, you do not need to specify a username to list
your crontab
entries.
Creating crontab entries
In this file, you can create entries that will execute certain commands. A
crontab
entry contains six fields:
- Minute (0 to 59)
- Hour (0 to 23)
- Day of the month (1 to 31)
- Month of the year (1 to 12)
- Day of the week (0 to 6); note that 0 indicates Sunday
A sixth field is possible. It refers to the
crontab
schedule you are actually creating. However, you should focus on the five
entries in the above bullet points. As with many other UNIX commands, you can use the wildcard command to indicate any and all times.
The wildcard is indicated with an asterisk (*). For example, the following
crontab
entry would execute the
nmap
program every Sunday at 5:15 a.m:
15 5 * * 0 nmap localhost
You can enter multiple values within each entry, as long as you use a comma. For example, you can enter the following to run
nmap
at 5:15 and 6:15 a.m. every Friday and Saturday:
15 5,6 * * 5,6 nmap localhost
The following entry would display the system time every 20 minutes:
1,21,41 * * * * (echo -n " "; date; echo) > /dev/con1