Automation with cron and at
In any operating system, it is possible to create jobs that you want to reoccur. This process, known as job scheduling, is usually done based on user-defined jobs. For Red Hat, this process is handled by the cron service, which can be used to schedule tasks (also called jobs). By default, Red Hat comes with a set of predefined jobs that occur on the system (hourly, daily, weekly, monthly, and with arbitrary periodicity). As an administrator, however, you can define your own jobs and allow your users to create them as well.
- Step 1. Although the cron package is installed by default, check to make sure it is installed on your system:
# rpm -qa | grep cron cronie-1.4.4-2.el6.x86_64 cronie-anacron-1.4.4-2.el6.x86_64 crontabs-1.10-32.1.el6.noarch
- Step 2. If, for some reason, the package isn't installed, install it now:
# yum install -y cronie cronie-anacron crontabs
- Step 3. Verify that the cron service is currently running:
# service crond status crond (pid 2239) is running...
- Step 4. Also verify that the service is set to start when the system boots:
# chkconfig --list crond crond 0:off 1:off 2:on 3:on 4:on 5:on 6:off
To start working with cron, you first need to look at the two config files that control access to the cron service. These two files are:
The /etc/cron.allow file:
- If it exists, only these users are allowed (cron.deny is ignored).
- If it doesn't exist, all users except cron.deny are permitted.
The /etc/cron.deny file:
- If it exists and is empty, all users are allowed (Red Hat Default).
For both files:
- If neither file exists, root only.
Creating cron Jobs
The default setting for Red Hat allows any user to create a cron job. As the root user, you also have the ability to edit and remove any cron job you want. Let's jump into creating a cron job for the system. You can use the crontab command to create, edit, and delete jobs.
Syntax: crontab [-u user] [option]
Edits the user's crontab
Lists the user's crontab
Deletes the user's crontab
Prompts before deleting the user's crontab
Before you start using the crontab command, however, you should look over the format it uses so you understand how to create and edit cron jobs. Each user has her own crontab file in /var/spool/cron (the file for each user is created only after the user creates her first cron job), based on the username of each user. Any "allow" actions taken by the cron service are logged to /var/log/cron.
View the /etc/crontab file to understand its syntax:
# grep ^# /etc/crontab # For details see man 4 crontabs # Example of job definition: # .---------------- minute (0 - 59) # | .------------- hour (0 - 23) # | | .---------- day of month (1 - 31) # | | | .------- month (1 - 12) OR jan,feb,mar,apr ... # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,etc. # | | | | | # * * * * * command to be executed
This file clearly spells out the values that can exist in each field. You must make sure that you provide a value for each field; otherwise, the crontab will not be created. You can also define step values by using */<number to step by>. For example, you could put */5 in the minute field to mean every fifth minute.
The best way to understand these fields is to create a crontab file and make some sample jobs. Using a text editor, create the following file in the /tmp directory.
Sample script for cron:
# nano /tmp/sample_script #!/bin/bash # # Send a msg to all users on the console # wall "Hello World"
Save the file and set the following permissions:
# chmod 775 /tmp/sample_script
Now create a cron job to launch the sample script. Because you are using the root user account, you can create a crontab for the normal user account user01.
- Step 1. Set up user01's crontab:
# crontab -u user01 -e
- Step 2. Add the following line:
* * * * * /tmp/sample_script
- Step 3. Save the file and quit the editor. Because you are using * in every field to test, in about 60 seconds you will see the script execute, and it should display "Hello World" on your screen. Obviously, you don't want messages every 60 seconds on your system, but you get the idea of how cron and crontab should work. Let's list the current jobs that user01 has set up, and you should see the job just created (do this just for verification purposes).
- Step 4. List the current cron jobs of user01:
# crontab -u user01 -l * * * * * /tmp/sample_scriptYou can now edit the crontab again to remove the single line, effectively deleting that individual job, or you can just delete the user's crontab entirely.
- Step 5. To remove a user's crontab jobs, use the following command:
# crontab -u user01 -r
- Step 6. You can verify the activity on different crontabs by...wait for it...looking at the log files!
# tail /var/log/cron Sep 10 09:08:01 new-host crond: (user01) CMD (/tmp/sample_script) Sep 10 09:08:38 new-host crontab: (root) LIST (user01) Sep 10 09:09:01 new-host crond: (user01) CMD (/tmp/sample_script) Sep 10 09:10:01 new-host crond: (user01) CMD (/tmp/sample_script) Sep 10 09:11:01 new-host crond: (user01) CMD (/tmp/sample_script) Sep 10 09:12:01 new-host crond: (user01) CMD (/tmp/sample_script) Sep 10 09:13:01 new-host crond: (user01) CMD (/tmp/sample_script) Sep 10 09:13:06 new-host crontab: (root) LIST (user01) Sep 10 09:14:01 new-host crond: (user01) CMD (/tmp/sample_script) Sep 10 09:14:15 new-host crontab: (root) DELETE (user01)
You can see that the cron service is executing the /tmp/sample_script file, and you can see the action after you deleted it. The process of creating crontabs and scheduling jobs is the same for all users on the system, including the root user.
Here is what the /etc/crontab file looks like for RHEL5 systems:
# cat /etc/crontab SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root HOME=/ # run-parts 01 * * * * root run-parts /etc/cron.hourly 02 4 * * * root run-parts /etc/cron.daily 22 4 * * 0 root run-parts /etc/cron.weekly 42 4 1 * * root run-parts /etc/cron.monthly
Here, the root user is defined to run the specified commands. This user field is now optional in RHEL6.
What do you think happens if you set up cron jobs to run during the night (say, to run some reports) and you shut down the system right before you go home? Well, it turns out that there is another great feature of cron. The /etc/anacrontab file defines jobs that should be run every time the system is started. If your system is turned off during the time that a cron job should have run, when the system boots again, the cron service will call /etc/anacrontab to make sure that all missed cron jobs are run.
Let's look at the /etc/anacrontab file:
# cat anacrontab SHELL=/bin/sh PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root # the maximal random delay added to the base delay of the jobs RANDOM_DELAY=45 # the jobs will be started during the following hours only START_HOURS_RANGE=3-22 #period in days delay in minutes job-identifier command 1 5 cron.daily nice run-parts /etc/cron.daily 7 25 cron.weekly nice run-parts /etc/cron.weekly @monthly 45 cron.monthly nice run-parts /etc/cron.monthly
The comments in this file make it easy to understand how jobs are defined. If your system is constantly on and you don't require anacron to be run, you can uninstall the cronie-anacron package, which controls just the anacron commands for the cron service.
For RHEL5, you need to ensure that this service is set to run when the system boots in order for it to be effective:
# chkconfig anacron—list anacron 0:off 1:off 2:on 3:on 4:on 5:on 6:off
Single Jobs with at
Although you can use the cron service to schedule jobs that you want to occur more than once, you can use a service called atd for single-instance jobs.
- Step 1. As with any service thus far, you need to verify that the package is installed:
# rpm -qa | grep ^at at-3.1.10-42.el6.x86_64
- Step 2. Check that the service is currently running:
# service atd status atd (pid 2300) is running...
- Step 3. Finally, verify that the service is set to start on system boot:
# chkconfig --list atd atd 0:off 1:off 2:off 3:on 4:on 5:on 6:off
The atd service uses two files in the same manner that cron does to control access to the service. These files are
The /etc/at.allow file:
- If it exists, only these users are allowed (at.deny is ignored).
- If it doesn't exist, all users except at.deny are permitted.
The /etc/at.deny file:
- If it exists and is empty, all users are allowed (Red Hat default).
For both files:
- If neither file exists, root only.
The atd service also includes a single command, at, that is used to set up the jobs you want to run.
Syntax: at [options]
Lists all jobs in the queue
Removes a job from the queue
Sends mail to the user when the job is complete
Reads input from the file
Shows the time the job will be executed
The at command enables you to specify a time in many different formats, making it really flexible. Let's look at a few examples of the time formats you can use:
# at 9am # at now + 3 days # at 1:30 3/22/10
After you specify a time, your command prompt changes:
# at 10:07am at>
Now you just need to enter any commands that you want to execute for your job at the specified time. You can finish by pressing Ctrl+D to end the command input and send the job to the queue:
# at 10:07am at> at> wall "Hello World" at> <EOT>
Now that a job is queued, let's view what the file that holds this job looks like.
- Step 1. Query the /var/spool/at directory for jobs:
# ls /var/spool/at a000010147997f spoolUnlike with the cron service, the names of the at jobs aren't really meaningful. Instead of viewing the directory that holds the at jobs, you might find it easier to list the jobs waiting to be run like you did with the cron service.
- Step 2. View the currently queued jobs using the at command:
# at -l 1 2010-10-27 10:07 a root
- Step 3. You can also use the atq command for the exact same results:
# atq 1 2010-10-27 10:07 a rootYou can see one job currently in the queue was sent by the root user and is waiting to run at 10:07 a.m. Instead of typing out all the jobs you might want to run, you could also use the -f option to specify a file containing a list of commands that you want executed instead:
# at -f cmds_file 11pmWhen you put jobs in the queue, notice that they are given ID numbers. This information is important in case there is a job that you want to delete from the queue.
- Step 4. Add a temporary job to the queue:
# cd ~ # touch test_job && chmod 775 test_job # at –f test_job 11pm
- Step 5. Verify that the job made it to the queue:
# atq 1 2010-12-04 23:00 a root
- Step 6. Delete the job from the queue:
# at -d 1
- Step 7. You can also use the atrm command to achieve the same results:
# atrm 1
- Step 8. Verify that the job is truly gone:
You should now be able to schedule single jobs and reoccurring jobs. Job management is important in making sure that your system runs smoothly. It also helps when you're automating tasks so you don't have to do them every day.