In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how to use cron to plan tasks in Linux. It is very detailed and has a certain reference value. Friends who are interested must finish 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-e SHELL=/bin/bash MAILTO=root@example.com PATH=/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 external 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 clock 03 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 * cron job I use is to perform a dnf or yum update that runs at 04:25 on the * day of every month, but I comment it out and won'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 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 "one day of each month", so the alternative is to use the * day of the next month, as shown below (it is assumed that when the job is ready to run, the data required for the report is ready).
02 03 1 1, 4, 7, 10 * / usr/local/bin/reports.sh
Run this cron job on the * * day of the following month at 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 * examples 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 1 # Generate a daily summary of process accounting at 23:53 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 * 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 jobs SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root 01 * 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/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 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 run the program at regular intervals, starting at a specified time, for example, from 3:00 in the morning (see the START_HOURS_RANGE line in the script above), from Sunday (* * days of the week), and * days 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.
The above is all the contents of the article "how to use cron to Plan tasks in Linux". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.