Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Explain in detail how to use cron to plan tasks in Linux

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

No time to run commands? Using cron's scheduled tasks means you don't have to stay up late to run the program.

One of the challenges for system administrators (among many benefits) is to run some tasks when you should go to bed. For example, some tasks, including those that run periodically, need to be run when no one is using computer resources, such as midnight or weekends. After work, I don't have time to run commands or scripts. Also, I don't want to start backups or major updates at night.

Instead, I use two service functions to run commands, programs, and tasks at my scheduled time. Cron and at services allow system administrators to schedule tasks to run at a specific time in the future. The at service specifies that a task should be run at some time. Cron services can schedule tasks to repeat in a cycle, such as day, week, or month.

In this article, I will introduce the cron service and how to use it.

Common (and unusual) cron uses

I use the cron service to schedule common things, such as regular backups that take place at 2:00 every morning, and I also use it to do unusual things.

The system clock on many computers (for example, operating system time) is set to use the Network time Protocol (NTP). After NTP sets the system time, it does not set the hardware clock, it may "drift". I use cron to set the hardware clock based on system time. I also have a Bash program that I run every morning to create a new "MOTD" on each computer. It contains useful information such as current disk usage. Many system processes and services, such as Logwatch, logrotate, and Rootkit Hunter, use cron services to schedule tasks and run programs every day.

The crond daemon is a background service that completes the cron function.

The cron service checks the files in the / var/spool/cron and / etc/cron.d directories, as well as the / etc/anacrontab file. The contents of these files define cron jobs that run at different intervals. The cron files for individual users are located in / var/spool/cron, while the cron job files generated by system services and applications are placed in the / etc/cron.d directory. / etc/anacrontab is a special case, which will be covered later in this article.

Use crontab

The cron utility runs based on a command specified in the cron table (crontab). Every user, including root, has a cron file. These files do not exist by default. But you can use the crontab-e command to create it in the / var/spool/cron directory, or you can use this command to edit a cron file (see the script below). I strongly recommend that you do not use standard editors (such as Vi, Vim, Emacs, Nano, or any other available editor). Using the crontab command not only allows you to edit the command, but also restarts the crond daemon when you save and exit the editor. The crontab command uses Vi as its underlying editor because Vi is preinstalled (at least in most basic installations).

Now that the cron file is empty, you must add the command from scratch. I add the job defined in the following example to my cron file, which is a quick guide so that I know what the various parts of the command mean, and you are free to copy it for your own use.

# crontab-eSHELL=/bin/bashMAILTO=root@example.comPATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin# 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# backup using the rsbu program to the internal 4TB HDD and then 4TB external01 01 * / usr/local/bin/rsbu-vbd1 / usr/local/bin/rsbu-vbd2# Set the hardware clock to keep it in sync with the more accurate system clock03 05 * / sbin/hwclock-- systohc# Perform monthly updates on the first of the month# 25 04 1 * * / usr/bin/dnf-y update

The crontab command is used to view or edit cron files.

The first three lines of the above code set a default environment. For a given user, the environment variable must be set, because cron does not provide an environment in any way. The SHELL variable specifies the shell under which the command runs. In this example, it is specified as Bash shell. The MAILTO variable sets the e-mail address at which the results of the cron job are sent. These emails provide the status of cron jobs (backups, updates, etc.), the same results you see when you run the program manually from the command line. The third behavior environment sets the PATH variable. But even if I set the path here, I always use the fully qualified path for each program.

In the above example, there are several comment lines that detail the syntax required to define a cron job. I'll explain each of these commands below, and then add more advanced features of the crontab file.

01 01 * / usr/local/bin/rsbu-vbd1; / usr/local/bin/rsbu-vbd2

Run a script on this line in my / etc/crontab to perform a backup of my system.

This line runs my own Bash shell script rsbu, which makes a full backup of my system. This job runs at 1:01 (01 01) every morning. The asterisk (*) in this position 3, 4, and 5 represents a specific time like a file wildcard. They represent "every day of the month", "every month" and "every day of the week". This line runs my backup twice, once to back up the internal dedicated hard drive and the other to back up the external USB drive, so I can be safe to use it.

In the next line I set a hardware clock that uses the current system clock as the source to set the hardware clock. This line is set to run at 5:03 every morning.

03 05 * / sbin/hwclock-systohc

This line uses system time as the source to set the hardware clock.

The third and last cron job I used was to perform a dnf or yum update, which ran at 04:25 on the first day of each month, but I commented it out and didn't run it again.

# 25 04 1 * * / usr/bin/dnf-y update

This line is used to perform a monthly update, but I also commented it out.

Other scheduled task skills

Now, let's do something more interesting than the basics. Suppose you want to run a special assignment at 3:00 every Thursday afternoon:

00 15 * * Thu / usr/local/bin/mycronjob.sh

The above line runs the mycronjob.sh script at 3:00 every Thursday afternoon.

Or maybe you need to run a quarterly report at the end of each quarter. The cron service does not set an option for the last day of each month, so the alternative is to use the first day of the next month, as shown below (assuming that the data required for the report is ready when the job is ready to run).

02 03 1 1, 4, 7, 10 * / usr/local/bin/reports.sh

Run this cron job on the first day of the month following the end of the quarter.

The job shown below runs every hour between 9:01 and 5:01 every day.

01 09-17 * / usr/local/bin/hourlyreminder.sh

Sometimes you want the job to run regularly during the business period.

I have a situation where I need to run my homework every two, three or four hours. It needs to be divided into hours at desired intervals, for example, * / 3 every three hours, or 6-18 shock 3 running every three hours from 6 a.m. to 6 p.m. The division of other time intervals is similar. For example, the expression * / 15 in the minute position means "run the job every 15 minutes."

* / 5 08-18 Compact 2 * / usr/local/bin/mycronjob.sh

This cron job runs every five minutes between 8:00 and 18:59

One thing to note is that the result of a division expression must be a remainder of 0 (that is, an integral division). In other words, in this example, the job is set to run every 5 minutes (08:00, 08:05, 08:10, 08:15) between 8 a.m. and 6 p.m. 18:55, etc.) instead of running in odd hours. In addition, this job cannot be run between 7:00 and 7:59 (LCTT translation note: the expression in this article is incorrect and modified according to the correct situation)

I'm sure you can think of many other possibilities based on these examples.

Restrict access to cron

Ordinary users may make mistakes when using cron access, for example, they may cause system resources (such as memory and CPU time) to be exhausted. To avoid this possible problem, the system administrator can restrict user access by creating a / etc/cron.allow file that contains a list of users allowed to create cron jobs. (whether listed in this list or not) cannot prevent root users from using cron.

By preventing non-root users from creating their own cron jobs, it may be necessary to add non-root users' cron jobs to root's crontab, "but wait!" You said, "Don't you run these jobs as root?" Not necessarily. In the first example in this article, the user name field that appears in the comment can be used to specify a user ID to run the job. This prevents jobs for specific non-root users from running as root. The following example shows a job definition that runs the job as the "student" user:

04 07 * student / usr/local/bin/mycronjob.sh

If no user is specified, the job will be run as the owner of the contab file, in this case root.

Cron.d

In the directory / etc/cron.d are some applications, such as the cron files installed by SpamAssassin and sysstat. Because there are no spamassassin or sysstat users here, these programs need a place to place the cron files, so they are placed in / etc/cron.d.

The / etc/cron.d/sysstat file below contains cron jobs related to the system activity report (SAR). These cron files are in the same format as the user cron files.

# Run system activity accounting tool every 10 minutes*/10 * root / usr/lib64/sa/sa1 1 "Generate a daily summary of process accounting at 2315 53 23 * root / usr/lib64/sa/sa2-A

The sysstat package installs the / etc/cron.d/sysstat cron file to run the program to generate SAR.

The sysstat cron file has two lines to perform tasks. The first line runs the sa1 program every ten minutes to collect data and stores it in a specified binary file in the / var/log/sa directory. Then, at 23:53 every evening, the sa2 program runs to create a daily summary.

Planning Tips

Some of the times I set in the crontab file seem random, and to some extent, they are. Trying to schedule cron assignments can be challenging, especially when the number of assignments is increasing. I usually have only a few tasks on each of my computers, which is much simpler than the computers in the production and experimental environments I use at work.

One of the systems I manage has 12 cron jobs running every night, and another 3 or 4 running on weekends or at the beginning of the month. That's a challenge, because if there are too many jobs running at the same time, especially the backup and compilation system, it will run out of memory and almost fill the swap file space, which can lead to system performance degradation or even overload. Nothing can be done in the end. I added some memory and improved how to plan tasks. I also deleted some poorly written tasks that used a lot of memory.

The crond service assumes that the host computer runs 24 hours a day. That means that if the computer is turned off during a scheduled run, these scheduled tasks will no longer run until their next scheduled run time. If there are critical cron jobs here, this can cause problems. Fortunately, there is another option for jobs that run regularly: anacron.

Anacron

The anacron program performs the same function as cron, but it increases the ability to run skipped jobs, for example, if the computer has been shut down or other reasons prevent the job from running in one or more cycles. It is very useful for laptops or other computers that are turned off or in sleep mode.

As soon as the computer is turned on and booted successfully, anacron will check to see if any planned assignments have been missed. If so, these jobs will run immediately, but only once (no matter how many loops it misses). For example, if a weekly job is shut down for the last three weeks because of a vacation, it will run as soon as your computer starts, but it will only run once, not three times.

The anacron program provides some options that are good for scheduling tasks periodically. It is a script installed in your / etc/cron. [hourly | daily | weekly | monthly] directory. Run according to the frequency they need.

How does it work? The next ones are a little simpler than the previous ones.

1. The crond service runs the cron job specified in / etc/cron.d/0hourly.

# Run the hourly jobsSHELL=/bin/bashPATH=/sbin:/bin:/usr/sbin:/usr/binMAILTO=root01 * root run-parts / etc/cron.hourly

The content in / etc/cron.d/0hourly causes the shell script located in / etc/cron.hourly to run.

2. The cron job specified in / etc/cron.d/0hourly runs the run-parts program every hour.

3. The run-parts program runs all scripts in the / etc/cron.hourly directory.

The / etc/cron.hourly directory contains the 0anacron script, which uses the following / etdc/anacrontab configuration file to run the anacron program.

# / etc/anacrontab: configuration file for anacron# See anacron (8) and anacrontab (5) for details.SHELL=/bin/shPATH=/sbin:/bin:/usr/sbin:/usr/binMAILTO=root# the maximal random delay added to the base delay of the jobsRANDOM_DELAY=45# the jobs will be started during the following hours onlySTART_HOURS_RANGE=3-22#period in days delay in minutes job-identifier command1 5 cron.daily nice run-parts / etc/cron.daily7 25 cron.weekly nice run-parts / etc/cron.weekly@monthly 45 cron.monthly nice run-parts / etc/cron.monthly

The contents of the / etc/anacrontab file run in the executable in the cron. [daily | weekly | monthly] directory at the appropriate time.

5. The anacron program runs the job located in / etc/cron.daily once a day. It runs jobs located in / etc/cron.weekly once a week. And run the jobs in cron.monthly once a month. Note that at the delay time specified on each line, it helps prevent these jobs from overlapping with other cron jobs.

I put them in the / usr/local/bin directory instead of the full Bash programs in the cron.X directory, which makes it easier for me to run them from the command line. Then, I add a symbolic link to the cron directory, for example, / etc/cron.daily.

Anacron programs are not designed to run programs at specified times. Instead, it is used to start at a specified time and run the program at regular intervals, for example, from 3:00 in the morning (see the START_HOURS_RANGE line in the script above), from Sunday (the first day of the week), and the first day of the month. If any one or more loops are missed, anacron will run the missed job immediately.

More about setting restrictions

I use many ways to run scheduled tasks on my computer. All of these tasks require a root permission to run. In my experience, few ordinary users need to run cron tasks. In one case, developers need a cron job to start a daily compilation of a development lab.

It is important to restrict non-root users to access cron functionality. However, in some special cases, users need to set a task to run at a pre-specified time, and cron allows them to do so. Many users do not understand how to properly configure cron to complete tasks, and they can make mistakes. These mistakes may be harmless, but this is often not the case, and they can cause problems. By setting function policies to make users and administrators cooperate with each other, individual cron jobs can not interfere with other users and system functions as much as possible.

You can set limits on the resources allocated to individual users or groups, but that's what you'll find in the next article.

For more information, all of this information describes how the cron system works on the man pages of cron, crontab, anacron, anacrontab, and run-parts.

The above is the whole content of this article, I hope it will be helpful to your study, and I also hope that you will support it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report