Chapter 12

Scheduling Tasks

The following topics are covered in this chapter:

The following RHCSA exam objective is covered in this chapter:

  • Schedule tasks using at and cron

On a Linux server it is important that certain tasks run at certain times. This can be done by using the at and cron services, which can be configured to run tasks in the future. The at service is for executing future tasks once only, and the cron service is for executing recurring regular tasks. Apart from these services, which have been around in all previous versions of RHEL, Systemd is providing timer units that can be used as an alternative. In this chapter you learn how to configure both cron and at, as well as Systemd timers.

“Do I Know This Already?” Quiz

The “Do I Know This Already?” quiz enables you to assess whether you should read this entire chapter thoroughly or jump to the “Exam Preparation Tasks” section. If you are in doubt about your answers to these questions or your own assessment of your knowledge of the topics, read the entire chapter. Table 12-1 lists the major headings in this chapter and their corresponding “Do I Know This Already?” quiz questions. You can find the answers in Appendix A, “Answers to the ‘Do I Know This Already?’ Quizzes and Review Questions.”

Table 12-1 “Do I Know This Already?” Section-to-Question Mapping

Foundation Topics Section

Questions

Understanding Task Scheduling Options in RHEL

1

Using Systemd Timers

2–4

Configuring cron to Automate Recurring Tasks

5–8

Configuring at to Schedule Future Tasks

9–10

1. What is the default solution for scheduling recurring jobs in RHEL 9?

  1. Systemd timers

  2. cron

  3. anacron

  4. at

2. How do you configure a timer to start at a specific time?

  1. Use a cron-style starting time notation in the [Timer] section.

  2. Use OnCalendar in the [Timer] section.

  3. Use OnTime in the [Timer] section.

  4. Schedule it through cron.

3. You want a timer to be started 1 minute after starting of the Systemd service. Which option do you use?

  1. OnCalendar

  2. OnUnitActiveSec

  3. OnBootSec

  4. OnStartupSec

4. You want a systemd user unit to be started 2 minutes after the user has logged in. Which of the following would you use?

  1. OnCalendar

  2. OnUserLogin

  3. OnUserActiveSec

  4. OnStartupSec

5. Which of the following would run a cron task Sunday at 11 a.m.?

  1. * 11 7 * *

  2. 0 11 * 7 *

  3. 0 11 * * 7

  4. 11 0 * 7 *

6. Which of the following launches a job every 5 minutes from Monday through Friday?

  1. */5 * * * 1-5

  2. */5 * 1-5 * *

  3. 0/5 * * * 1-5

  4. 0/5 * 1-5 * *

7. How do you create a cron job for a specific user?

  1. Log in as that user and type crontab -e to open the cron editor.

  2. Open the crontab file in the user home directory and add what you want to add.

  3. As root, type crontab -e username.

  4. As root, type crontab -u username -e.

8. Which of the following is not a recommended way to specify jobs that should be executed with cron?

  1. Modify /etc/crontab.

  2. Put the jobs in separate scripts in /etc/cron.d.

  3. Use crontab -e to create user-specific cron jobs.

  4. Put scripts in /etc/cron.{hourly|daily|weekly|monthly} for automatic execution.

9. After you enter commands in the at shell, which command enables you to close the at shell?

  1. Ctrl-V

  2. Ctrl-D

  3. exit

  4. :wq

10. Which command enables you to see current at jobs scheduled for execution?

  1. atrm

  2. atls

  3. atq

  4. at

Foundation Topics

Understanding Task Scheduling Options in RHEL

RHEL 9 offers different solutions for scheduling tasks:

  • Systemd timers are now the default solution to ensure that specific tasks are started at specific moments.

  • cron is the legacy scheduler service. It is still supported and responsible for scheduling a few services.

  • st is used to schedule an occasional user job for future execution.

Using Systemd Timers

Since its initial appearance in RHEL 7, systemd has been replacing many services. Since the release of RHEL 9 it is also responsible for scheduling tasks. It is now the primary mechanism to do so, which means that if ever you are trying to find out how future tasks are executed, you should consider systemd timers first.

A systemd timer is always used together with a service file, and the names should match. For example, the logrotate.timer file is used to modify the logrotate.service file. The service unit defines how the service should be started, and the timer defines when it will be started. If you need a service to be started by a timer, you enable the timer, not the service. Example 12-1 shows what the logrotate.timer file looks like.

Example 12-1 Sample Timer Contents

[root@server1 system]# systemctl cat logrotate.timer
# /usr/lib/systemd/system/logrotate.timer
[Unit]
Description=Daily rotation of log files
Documentation=man:logrotate(8) man:logrotate.conf(5)

[Timer]
OnCalendar=daily
AccuracySec=1h
Persistent=true

[Install]
WantedBy=timers.target

To define how the timer should be started, the timer unit contains a [Timer] section. In the code in Example 12-1, you can see that it lists three options:

  • OnCalendar: Describes when the timer should execute. In this case it is set to daily, which ensures daily execution.

  • AccuracySec: Indicates a time window within which the timer should execute. In Example 12-1 it is set to 1 hour. If the timer needs to be executed at a more specific time, it is common to set it to a lower value. Use 1us for the best accuracy.

  • Persistent: A modifier to OnCalendar=daily, it specifies that the last execution time should be stored on disk, so that the next time it executes is exactly one day later.

In systemd timers, different options can be used to indicate when the related service should be started. Table 12-2 lists the most important options.

An icon reads, Key Topic.

Table 12-2 Timing Options in Systemd Timers

Option

Use

OnActiveSec

Defines a timer relative to the moment the timer is activated.

OnBootSec

Defines a timer relative to when the machine was booted.

OnStartupSec

Specifies a time relative to when the service manager was started. In most cases this is the same as OnBootSec, but not when systemd user units are used.

OnUnitActiveSec

Defines a timer relative to when the unit that the timer activates was last activated.

OnCalendar

Defines timers based on calendar event expressions, such as daily. See man systemd.time for more details.

In Exercise 12-1 you’ll learn how to explore how systemd timers are organized.

Exercise 12-1: Using Systemd Timers

  1. Use systemctl list-units -t timer to show a list of all timers.

  2. Type systemctl list-unit-files logrotate.*, which should show there is a logrotate.service and a logrotate.timer.

  3. Enter systemctl cat logrotate.service to verify the contents of the logrotate.service unit file. Notice that it doesn’t have an [Install] section.

  4. Use systemctl status logrotate.service, which will show it marked as triggered by the logrotate.timer.

  5. Use systemctl status logrotate.timer to verify the status of the related timer.

  6. Install the sysstat package, using dnf install -y sysstat.

  7. Verify the unit files that were added from this package, using systemctl list-unit-files sysstat*.

  8. Type systemctl cat sysstat-collect.timer to show what the sysstat-collect timer is doing. You’ll see the line OnCalendar=*:00/10, which ensures that it will run every 10 minutes.

Configuring cron to Automate Recurring Tasks

Task scheduling has been common on Linux for a long time, and in the past the crond service was the primary tool to schedule tasks.

The crond service consists of two major components. First is the cron daemon crond, which in RHEL 9 is also started as a systemd service. This daemon looks every minute to see whether there is work to do. Second, this work to do is defined in the cron configuration, which consists of multiple files working together to provide the right information to the right service at the right time. In this section, you learn how to configure cron.

Exam Tip

Even if systemd timers are now the default solution for running recurring tasks, cron is still available. Make sure you master both for purposes of preparing for the RHCSA exam!

Managing the crond Service

The crond service is started by default on every RHEL system. Managing the crond service itself is easy: it does not need much management. Where other services need to be reloaded or restarted to activate changes to their configuration, this is not needed by crond. The crond daemon wakes up every minute and checks its configuration to see whether anything needs to be started.

To monitor the current status of the crond service, you can use the systemctl status crond command. Example 12-2 shows the output of this command.

Example 12-2 Monitoring the Current State of the crond Service

[root@localhost ~]# systemctl status crond
• crond.service - Command Scheduler
     Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2022-11-21 12:19:12 CET; 1h
  21min ago
   Main PID: 1169 (crond)
      Tasks: 2 (limit: 23284)
     Memory: 1.5M
        CPU: 66ms
     CGroup: /system.slice/crond.service
             ├─1169 /usr/sbin/crond -n
             └─6689 /usr/sbin/anacron -s
Nov 21 13:01:01 localhost.localdomain anacron[6689]: Will run job
  'cron.daily' in 12 min.
Nov 21 13:01:01 localhost.localdomain anacron[6689]: Will run job
  'cron.weekly' in 32 min.
Nov 21 13:01:01 localhost.localdomain anacron[6689]: Will run job
  'cron.monthly' in 52 min.
Nov 21 13:01:01 localhost.localdomain anacron[6689]: Jobs will be
  executed sequentially
Nov 21 13:01:01 localhost.localdomain run-parts[6691]: (/etc/cron.
  hourly) finished 0anacron
Nov 21 13:01:01 localhost.localdomain CROND[6675]: (root) CMDEND
  (run-parts /etc/cron.hourly)
Nov 21 13:13:01 localhost.localdomain anacron[6689]: Job 'cron.daily'
  started
Nov 21 13:13:01 localhost.localdomain anacron[6689]: Job 'cron.daily'
  terminated
Nov 21 13:33:01 localhost.localdomain anacron[6689]: Job 'cron.weekly'
  started
Nov 21 13:33:01 localhost.localdomain anacron[6689]: Job 'cron.weekly'
  terminated

The most significant part of the output of the systemctl status crond command is in the beginning, which indicates that the cron service is loaded and enabled. The fact that the service is enabled means that it will automatically be started whenever this service is restarting. The last part of the command output shows current status information. Through the journald service, the systemctl command can find out what is actually happening to the crond service.

Understanding cron Timing

When scheduling services through cron, you need to specify when exactly the services need to be started. In the crontab configuration (which is explained in more depth in the next section), you use a time string to indicate when tasks should be started. Table 12-3 shows the time and date fields used (in the order specified).

An icon reads, Key Topic.

Table 12-3 cron Time and Date Fields

Field

Values

minute

0–59

hour

0–23

day of month

1–31

month

1–12 (or month names)

day of week

0–7 (Sunday is 0 or 7), or day names

In any of these fields, you can use an * as a wildcard to refer to any value. Ranges of numbers are allowed, as are lists and patterns. Some examples are listed next:

An icon reads, Key Topic.
  • * 11 * * * Every minute between 11:00 and 11:59 (probably not what you want)

  • 0 11 * * 1-5 Every day at 11 a.m. on weekdays only

  • 0 7-18 * * 1-5 Every hour at the top of the hour between 7 a.m. and 6 p.m. on weekdays

  • 0 */2 2 12 5 Every two hours on the hour on December 2 and every Friday in December

Tip

You don’t need to remember all this; man 5 crontab shows all possible constructions.

Managing cron Configuration Files

The main configuration file for cron is /etc/crontab, but you will not change this file directly. It does give you a convenient overview, though, of some time specifications that can be used in cron. It also sets environment variables that are used by the commands that are executed through cron (see Example 12-3). To make modifications to the cron jobs, there are other locations where cron jobs should be specified.

Example 12-3 /etc/crontab Sample Content

[root@server2 ~]# cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# 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,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed

Instead of modifying /etc/crontab, different cron configuration files are used:

An icon reads, Key Topic.
  • cron files in /etc/cron.d

  • Scripts in /etc/cron.hourly, cron.daily, cron.weekly, and cron.monthly

  • User-specific files that are created with crontab -e

In this section, you get an overview of these locations.

Note

If you want to experiment with how cron works, you should allow for a sufficient amount of time for the job to be executed. The crond service reads its configuration every minute, after which new jobs can be scheduled for execution on the next minute. So, if you want to make sure your job is executed as fast as possible, allow for a safe margin of three minutes between the moment you save the cron configuration and the execution time.

To start, cron jobs can be started for specific users. To create a user-specific cron job, type crontab -e after logging in as that user, or as root type crontab -e -u username. These user-specific cron jobs are the most common way for scheduling additional jobs through cron.

When you are using crontab -e, the default editor opens and creates a temporary file. After you edit the cron configuration, the temporary file is moved to its final location in the directory /var/spool/cron. In this directory, a file is created for each user. These files should never be edited directly! When the file is saved by crontab -e, it is activated automatically.

Whereas in the early days of RHEL the /etc/crontab file was modified directly, on RHEL 9 you do not do that anymore. If you want to add cron jobs, you add these to the /etc/cron.d directory. Just put a file in that directory (the exact name does not really matter) and make sure that it meets the syntax of a typical cron job. In Example 12-4, you can see an example of the /etc/cron.d/0hourly.cron file, which takes care of running hourly jobs through cron.

Example 12-4 Example cron Jobs in /etc/cron.d

[root@server1 cron.d]# ls
0hourly
[root@server1 cron.d]# cat 0hourly
# Run the hourly jobs
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
01 * * * * root run-parts /etc/cron.hourly

This example starts by setting environment variables. These are the environment variables that should be considered while running this specific job. On the last line the job itself is defined. The first part of this definition specifies when the job should run. In this case it will run 1 minute after each hour, each day of the month, each month, and each day of the week. The job will be executed as the root user, and the job itself involves the run-parts command, which is responsible for running the scripted cron jobs in /etc/cron.hourly.

The last way to schedule cron jobs is through the following directories:

  • /etc/cron.hourly

  • /etc/cron.daily

  • /etc/cron.weekly

  • /etc/cron.monthly

In these directories, you typically find scripts (not files that meet the crontab syntax requirements) that are put in there from RPM package files. When opening these scripts, notice that no information is included about the time when the command should be executed. The reason is that the exact time of execution does not really matter. The only thing that does matter is that the job is launched once an hour, once a day, a week, or a month, and anacron is taking care of everything else.

Understanding the Purpose of anacron

To ensure regular execution of the job, cron uses the anacron service. This service takes care of starting the hourly, daily, weekly, and monthly cron jobs, no matter at which exact time. To determine how this should be done, anacron uses the /etc/anacrontab file. Example 12-5 shows the contents of the /etc/anacrontab file, which is used to specify how anacron jobs should be executed.

Example 12-5 anacrontab Configuration

[root@server1 spool]# cat /etc/anacrontab
# /etc/anacrontab: configuration file for anacron

# See anacron(8) and anacrontab(5) for details.

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

In /etc/anacrontab, the jobs to be executed are specified in lines that contain four fields, as shown in Example 12-5. The first field specifies the frequency of job execution, expressed in days. The second field specifies how long anacron waits before executing the job, which is followed by the third field that contains a job identifier. The fourth field specifies the command that should be executed.

Tip

Although it’s useful to know how anacron works, it typically is not a service that is configured directly. The need to configure services through anacron is taken away by the /etc/cron.hourly, cron.daily, cron.weekly, and cron.monthly files.

Note

It is not easy to get an overview of the cron jobs actually scheduled for execution. There is no single command that would show all currently scheduled cron jobs. The crontab -l command does list cron jobs, but only for the current user account.

Managing cron Security

By default, all users can enter cron jobs. It is possible to limit which user is allowed to schedule cron jobs by using the /etc/cron.allow and /etc/cron.deny configuration files. If the cron.allow file exists, a user must be listed in it to be allowed to use cron. If the /etc/cron.deny file exists, a user must not be listed in it to be allowed to set up cron jobs. Both files should not exist on the same system at the same time. Only root can use cron if neither file exists.

In Exercise 12-2, you apply some of the cron basics and schedule cron jobs using different mechanisms.

Exercise 12-2 Running Scheduled Tasks Through cron

  1. Open a root shell. Type cat /etc/crontab to get an impression of the contents of the /etc/crontab configuration file.

  2. Type crontab -e. This opens an editor interface that by default uses vi as its editor. Add the following line:

    0 2 * * 1-5 logger message from root
  3. Use the vi command :wq! to close the editing session and write changes.

  4. Type cd /etc/cron.hourly. In this directory, create a script file with the name eachhour that contains the following line:

    logger This message is written at $(date)
  5. Use chmod +x eachhour to make the script executable; if you fail to make it executable, it will not work.

  6. Enter the directory /etc/crond.d and in this directory create a file with the name eachhour. Put the following contents in the file:

    11 * * * * root logger This message is written from /etc/cron.d
  7. Save the modifications to the configuration file and continue to the next section. (For optimal effect, perform step 8 after a couple of hours.)

  8. After a couple of hours, type grep written /var/log/messages and read the messages to verify correct cron operations.

Configuring at to Schedule Future Tasks

Whereas cron is used to schedule jobs that need to be executed on a regular basis, the atd service is available for services that need to be executed only once. On RHEL 9, the atd service is available by default, so all that you need to do is schedule jobs.

To run a job through the atd service, you would use the at command, followed by the time the job needs to be executed. This can be a specific time, as in at 14:00, but it can also be a time indication like at teatime or at noon. After you type this, the at shell opens. From this shell, you can type several commands that will be executed at the specific time that is mentioned. After entering the commands, press Ctrl-D to quit the at shell.

After scheduling jobs with at, you can use the atq command (q for queue) to get an overview of all jobs currently scheduled. It is also possible to remove current at jobs. To do this, use the atrm command, optionally followed by the number of the at job that you want to remove. In Exercise 12-3, you learn how to work with at to schedule jobs for execution at a specific time.

Tip

The batch command works like at, but it’s a bit more sophisticated. When using batch, you can specify that a job is started only when system performance parameters allow. Typically, that is when system load is lower than 0.8. This value is a bit low on modern multi-CPU systems, which is why the load value can be specified manually when starting atd, using the -l command-line option. Use, for instance, atd -l 3.0 to make sure that no batch job is started when the system load is higher than 3.0.

Exercise 12-3 Scheduling Jobs with at

  1. Type systemctl status atd. In the line that starts with Loaded:, this command should show you that the service is currently loaded and enabled, which means that it is ready to start receiving jobs.

  2. Type at 15:00 (or replace with any time near to the time at which you are working on this exercise).

  3. Type logger message from at. Press Ctrl-D to close the at shell.

  4. Type atq to verify that the job has indeed been scheduled.

Summary

In this chapter, you learned how to schedule jobs for future execution. RHEL 9 provides three solutions to do so: systemd timers have become the default solution, the legacy cron service is still around, and at can be used to schedule deferred user tasks.

Exam Preparation Tasks

As mentioned in the section “How to Use This Book” in the Introduction, you have several choices for exam preparation: the end-of-chapter labs; the memory tables in Appendix C; Chapter 27, “Final Preparation”; and the practice exams.

Review All Key Topics

Review the most important topics in the chapter, noted with the Key Topic icon in the margin of the page. Table 12-4 lists a reference for these key topics and the page number on which each is found.

An icon reads, Key Topic.

Table 12-4 Key Topics for Chapter 12

Key Topic Element

Description

Page

Table 12-2

Timing Options in Systemd Timers

275

Table 12-3

cron Time and Date Fields

278

List

crontab time indicators examples

278

List

Methods to enter crontab information

279

Define Key Terms

Define the following key terms from this chapter and check your answers in the glossary:

timer

crond

anacron

at

Review Questions

The questions that follow are meant to help you test your knowledge of concepts and terminology and the breadth of your knowledge. You can find the answers to these questions in Appendix A.

1. Where do you configure a cron job that needs to be executed once every two weeks?

2. How do you configure a service to be started 5 minutes after your system has started?

3. You have enabled a systemd service unit file to be started by a timer, but it doesn’t work. What should you check?

4. What is the easiest way to start a service every 7 hours?

5. How do you match a specific timer to a specific service?

6. Which command enables you to schedule a cron job for user lisa?

7. How do you specify that user boris is never allowed to schedule jobs through cron?

8. You need to make sure that a job is executed every day, even if the server at execution time is temporarily unavailable. How do you do this?

9. Which service must be running to schedule at jobs?

10. Which command enables you to find out whether any current at jobs are scheduled for execution?

End-of-Chapter Lab

In this end-of-chapter lab, you work on at jobs and on cron jobs.

Lab 12.1

  1. Create a cron job that performs an update of all software on your computer every evening at 11 p.m.

  2. Schedule your machine to be rebooted at 3 a.m. tomorrow morning.

  3. Use a systemd timer to start the vsftpd service five minutes after your system has started.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset