Linux tips: Scheduling jobs with Cron and at
On Linux systems, many administrative tasks must be performed frequently and regularly. These tasks include rotating log files to avoid filling the file system, backing up data, and connecting time servers to perform system time synchronization. The tutorials mentioned above describe these administrative tasks in more detail. In this article, learn about the scheduling mechanisms available in Linux, including cron and anacron facilities, as well as crontab and at commands. Even if the system is often shut down, Anacron can also help with scheduling jobs.
Run a job at a certain time interval
Running a job at a certain time interval requires management with a cron facility, which consists of the Crond daemon and a set of tables that describe what to do and what frequency to take. This daemon wakes up once every minute and checks crontab to determine what needs to be done. The user manages crontab using the crontab command. The Crond daemon is often started by the INIT process when the system starts.
For simplicity, suppose you want to run the command shown in Listing 1 on a regular basis. This command actually reports only the date and time, and nothing else is done, but it shows you how to set up cron jobs using crontab, and you can also see how long jobs run by the output. Setting the Crontab entry requires a string containing escaped shell metacharacters, so it is suitable for simple commands and parameters. In this example, the Echo command is run from script/home/ian/mycrontab.sh, and the script does not require parameters. This can reduce the work of handling escape characters.
Listing 1. A simple example of a command
[email protected] ~]$ cat mycrontest.sh
#!/bin/bash
echo "It is today $ (date +%t) on $ (date +%a)"
[Email protected] ~]$./mycrontest.sh
It's now 18:37:42 on Friday
Create Crontab
Use the crontab command and the-E (for "edit") option to create the crontab. This opens the VI editor unless another editor is specified in the editor or VISUAL environment variable.
Each crontab entry consists of six fields:
Minutes
Hours
Day
Month
Week
String executed by SH
The range of minutes and hours is 0-59 and 0-12, respectively, and the day and month ranges are 1-31 and 1-12, respectively. The range of the week is 0-6,0, which represents Sunday. The week can also be designated as Sun, Mon, Tue, and so on. The 6th field contains everything after the first 5 fields, which is the string to pass to SH. The percent semicolon (%) is converted to a blank line, so if you want to use% or any other special character, precede it with a backslash (\). A line before the first% is passed to the shell, and all rows after that% are passed as standard input.
Each time-related field can specify a single value, a range of values (such as 0-10 or sun-wed), or a comma-delimited list of individual values and ranges. Listing 2 shows an example of an crontab entry.
Listing 2. A simple example of crontab
0,20,40 22-23 * 7 fri-sat/home/ian/mycrontest.sh
In this example, our commands are executed in the No. 0, 20, 40 minutes (every 20 minutes) between 10 o'clock and midnight in every Friday and Saturday night in July. For details on other ways of specifying the time, see the man page of Crontab (5).
Output
You might want to know what to do with the output from the command. Most commands designed to use cron use Syslog to record output in the log. However, the output directed to stdout is sent to the user by e-mail. Listing 3 shows the output that our command example might produce.
Listing 3. Cron output sent by e-mail
From [email protected] Fri Jul 6 23:00:02 2007
Date:fri, 6 Jul 2007 23:00:01-0400
From: [Email protected] (Cron Daemon)
To: [Email protected]
Subject:cron <[email protected]>/home/ian/mycrontest.sh
Content-type:text/plain; Charset=utf-8
auto-submitted:auto-generated
X-cron-env: <SHELL=/bin/sh>
X-cron-env: <HOME=/home/ian>
X-cron-env: <PATH=/usr/bin:/bin>
X-cron-env: <LOGNAME=ian>
X-cron-env: <USER=ian>
It's now 23:00:01 on Friday
Where is the crontab stored?
The crontab created with the crontab command is stored in a subdirectory below/etc/spool/cron, which has the same name as the user who created the crontab, so the above crontab is stored in/etc/spool/cron/ian. Therefore, as with the passwd command, the crontab command is a suid program that runs with root privileges.
/etc/crontab
In addition to user crontab files in/var/spool/cron, Cron also checks files in/etc/crontab files and/ETC/CRON.D directories. In these system crontab, a field is added between the Fifth Time field (week) and the command. This field specifies which user should run this command, typically the root user. Listing 4 shows an example of a/etc/crontab file.
Listing 4. /etc/crontab
Shell=/bin/bash
Path=/sbin:/bin:/usr/sbin:/usr/bin
Mailto=root
home=/
# Run-parts
* * * * * Root run-parts/etc/cron.hourly
4 * * * Root run-parts/etc/cron.daily
4 * * 0 root run-parts/etc/cron.weekly
4 1 * * Root run-parts/etc/cron.monthly
In this example, the real work is performed by the Run-parts command, which runs scripts in directories such as/etc/cron.hourly,/etc/cron.daily, and/etc/crontab only controls when the job is executed. Note that all commands here are run as root users. Also note that crontab can include shell variable assignments, which are executed before the command is run.
Anacron
Cron is suitable for those systems that run continuously. For systems that do not boot often, such as laptops, you can use another utility, Anacron ("anachronistic cron"), to schedule daily, weekly, or monthly jobs. Anacron does not process jobs that are executed hourly.
Anacron keeps a timestamp file in/var/spool/anacron, recording when the job runs. When Anacron runs, it checks whether the required number of days has elapsed since the last run of the job and, if necessary, runs the job. Anacron's job table is stored in/etc/anacrontab and the file format is slightly different from/etc/crontab. As with/etc/crontab,/etc/anacrontab can contain environment settings. There are four fields per job:
Cycle
Delay
Job identifier
Command
The period is the number of days, but can be specified as a @monthly, which ensures that the job runs only once per month (regardless of the number of days in this month). A delay is the number of minutes that the job waits before it actually starts before it meets the running condition. You can use this setting to prevent the centralized execution of jobs at system startup. The job identifier can contain all non-whitespace characters except the slash (/).
Both/etc/crontab and/etc/anacrontab are updated through direct editing. Files in these files or/ETC/CRON.D directories are not updated with the crontab command.
Run a job at a specified time
Sometimes, you need to run the job only once rather than periodically. To do this, you should use the AT command. The command to run is read from the file specified by the-F option and read from stdin if no-f is used. The-m option sends a message to the user, even if the command is not stdout. The-V option displays when the job was run. This time is also shown in the output.
Listing 5 shows an example of running a mycrontest.sh script. Listing 6 shows the output that is sent to the user by mail after the job is run. Note that the output here is simpler than the corresponding cron job output.
Listing 5. Using the AT command
[Email protected] ~]$ at-f mycrontest.sh-v 10:25
Sat Jul 7 10:25:00 2007
Job 5 at Sat 7 10:25:00 2007
Listing 6. Job output from at
From [email protected] Sat 7 10:25:00 2007
Date:sat, 7 Jul 2007 10:25:00-0400
From:ian Shields <[email protected]>
Subject:output from your job 5
To: [Email protected]
It's now 10:25:00 on Saturday
The time setting can be very complex. Listing 7 shows a few examples. See the AT-hand-albums,/usr/share/doc/at/timespec files, or/usr/share/doc/at-3.1.10/timespec files (the 3.1.10 in this example is the version number of the at package).
Listing 7. The time value used by the AT command
[Email protected] ~]$ at-f mycrontest.sh 10pm Tomorrow
Job in Sun Jul 8 22:00:00 2007
[Email protected] ~]$ at-f mycrontest.sh-Tuesday
Job at Tue Jul 10 02:00:00 2007
[Email protected] ~]$ at-f mycrontest.sh July 11
Job at Wed Jul 11 02:00:00 2007
[Email protected] ~]$ at-f mycrontest.sh-Next week
Job 14 at Sat Jul 02:00:00 2007
Manage Scheduled jobs
List the scheduled jobs
You can manage cron and at jobs. Using the crontab command and the-l option to list crontab, use the ATQ command to display the jobs that are queued with the AT command, as shown in Listing 8.
Listing 8. Show scheduled jobs
[Email protected] ~]$ crontab-l
0,20,40 22-23 * 7 fri-sat/home/ian/mycrontest.sh
[Email protected] ~]$ ATQ
Wed Jul 02:00:00 a Ian
* Sat Jul 02:00:00 a Ian
Sun Jul 8 22:00:00 a Ian
Tue Jul 02:00:00 a Ian
If you want to see the actual commands executed at the AT schedule, you can use the AT command with the-C option and the job number. You will notice that most of the environment settings that take effect when the AT command is issued are saved with the scheduled job. Listing 9 shows a partial output of job 15 in Listing 7 and listing 8.
Listing 9. Use at-c and add job number
#!/bin/sh
# Atrun uid=500 gid=500
# Mail Ian 0
Umask 2
hostname=lyrebird.raleigh.ibm.com; Export HOSTNAME
Shell=/bin/bash; Export SHELL
histsize=1000; Export Histsize
Ssh_client=9.67.219.151\ 3210\ 22; Export Ssh_client
SSH_TTY=/DEV/PTS/5; Export Ssh_tty
User=ian; Export USER
...
Home=/home/ian; Export HOME
Logname=ian; Export LOGNAME
...
Cd/home/ian | | {
echo ' Execution directory inaccessible ' >&2
Exit 1
}
${SHELL:-/BIN/SH} << ' (dd if=/dev/urandom count=200 bs=1 \
2>/dev/null| Lc_all=c tr-d-C ' [: alnum:] ') '
#!/bin/bash
echo "It is today $ (date +%t) on $ (date +%a)"
Note that the contents of our script file have been copied in a here-document, and this here-document will be executed by the shell specified by the shell variable (using/bin/sh if the shell variable is not set).
Delete a scheduled job
You can delete all scheduled cron jobs using the cron command and the-r option, as shown in Listing 10.
Listing 10. Display and delete cron jobs
[Email protected] ~]$ crontab-l
0,20,40 22-23 * 7 fri-sat/home/ian/mycrontest.sh
[Email protected] ~]$ Crontab-r
[Email protected] ~]$ crontab-l
No crontab for Ian
To delete a system cron or anacron job, you should edit/etc/crontab,/etc/anacrontab, or edit or delete files in the/ETC/CRON.D directory.
You can use the ATRM command plus job number to delete one or more jobs that are scheduled with the AT command. Multiple jobs should be separated by white space. Listing 11 shows an example.
Listing 11. Display and delete jobs with ATQ and ATRM
- This article is from: Linux Learning Tutorial Network
Linux tips: Scheduling jobs with Cron and at