Home > Articles > Certification > Other IT

This chapter is from the book

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:

  • /etc/cron.allow
  • /etc/cron.deny

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]

Options:

-e

Edits the user's crontab

-l

Lists the user's crontab

-r

Deletes the user's crontab

-i

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_script
    
    You 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[4213]: (user01) CMD (/tmp/sample_script)
    Sep 10 09:08:38 new-host crontab[4220]: (root) LIST (user01)
    Sep 10 09:09:01 new-host crond[4224]: (user01) CMD (/tmp/sample_script)
    Sep 10 09:10:01 new-host crond[4230]: (user01) CMD (/tmp/sample_script)
    Sep 10 09:11:01 new-host crond[4236]: (user01) CMD (/tmp/sample_script)
    Sep 10 09:12:01 new-host crond[4242]: (user01) CMD (/tmp/sample_script)
    Sep 10 09:13:01 new-host crond[4248]: (user01) CMD (/tmp/sample_script)
    Sep 10 09:13:06 new-host crontab[4251]: (root) LIST (user01)
    Sep 10 09:14:01 new-host crond[4253]: (user01) CMD (/tmp/sample_script)
    Sep 10 09:14:15 new-host crontab[4258]: (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

  • /etc/at.allow
  • /etc/at.deny

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]

Options:

-l

Lists all jobs in the queue

-d ID

Removes a job from the queue

-m

Sends mail to the user when the job is complete

-f FILE

Reads input from the file

-v

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  spool
    
    Unlike 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 root
    
    You 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 11pm
    
          
    When 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:
    # atq
    
          

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020