Introduction to Linux basic commands 14: scheduled tasks

Time:2022-4-28

In the process of using the computer, there are often some planned tasks that need to be executed at some time in the future. Linux provides some methods to set themScheduled task

1、at

commandatRead the command from the file or standard input and execute it at a future time, only once.atThe normal execution of requires a daemonatd(for systemctl, seeThis one):

#Install at
Yum install - y at or apt get install at - y
#Start daemon
Service ATD start or systemctl start ATD
#Check whether to start
Chkconfig -- list|grep ATD or systemctl list unit files|grep ATD
#Set startup
Chkconfig -- level 235 ATD on or systemctl enable ATD

If pipes are not used|Or specify options-fIf so,atThe execution of will be interactive. You need to enter the command at the prompt of at:

[ [email protected] Temp]# at now + 2 minutes # execute at and specify the execution time as the last two minutes of the current time
At > echo Hello world > / root / temp / file # manually enter the command and press enter
At > < EOT > #ctrl + d end input
Job 9 at Thu Dec 22 14:05:00 2016 # display task number and execution time
[[email protected] temp]#

option-lOr commandatqQuery task

[[email protected] temp]# atq
9       Thu Dec 22 14:05:00 2016 a root

When the time arrives, the task is executed to generate a new file and save the output of echo

[[email protected] temp]# ls -l file 
-Rw-r -- R -- 1 root December 22 14:05 file
[[email protected] temp]# cat file 
hello world
[[email protected] temp]#

atThere are many ways to specify time, which can be
1)hh:mmHour: minute (on the same day, if the time has passed, it will be executed on the next day)
2)midnight(late at night),noon(noon),teatime(afternoon tea time, 4pm),today,tomorrowetc.
3) 12 hour timing system, added after timeam(morning) orpm(afternoon)
4) Specify specific execution datemm/dd/yy(month / day / year) ordd.mm.yy(day, month and year)
5) Relative timing methodnow + n unitsNow is the present time, n is the number, and units is the units (minutes, hours, days, weeks)
For example, create a directory at 2:20 p.m. tomorrow

[[email protected] temp]# at 02:20pm tomorrow
at> mkdir /root/temp/X
at> <EOT>
job 11 at Fri Dec 23 14:20:00 2016

option-dOr commandatrmIndicates deleting a task

[ [email protected] Temp]# at - D 11 # delete task 11 (example above)
[[email protected] temp]# atq
[[email protected] temp]#

Pipes can be used|Or options-fGive WayatGet tasks from standard input or files

[[email protected] temp]# cat test.txt 
echo hello world > /root/temp/file
[[email protected] temp]# at -f test.txt 5pm +2 days
job 12 at Sat Dec 24 17:00:00 2016
[[email protected] temp]# cat test.txt|at 16:20 12/23/16
job 13 at Fri Dec 23 16:20:00 2016

atdThrough two documents/etc/at.allowand/etc/at.denyTo determine which users in the system can useatSet a scheduled task, which checks first/etc/at.allow, if the file exists, only the users listed in the file (one user name per line) can use at; If not, check the file/etc/at.deny, all users who are not in this file can use at. If/etc/at.denyIf it is an empty file, it means that all users in the system can use at; If/etc/at.denyIf the file does not exist, only root can use at.

2、crontab

commandcrontabUsed to set, remove and list servicescrondForms,crondServices work similarlyatd, the difference iscrondYou can set the task to execute multiple times. Relatively speakingatdMore commonly used.

You also need to start the servicecrond

[[email protected] temp]# ps -ef|grep [c]rond
Root 733 1 0 December 20? 00:00:00 /usr/sbin/crond -n

Each user in the system can have their owncron table, sameatdsimilar,crondThere are also two files/etc/cron.allowand/etc/cron.denyIt is used to restrict users from using cron, and the rules are also consistent withatdThe two files are the same.

option-lIndicates the cron table entry that lists the current user
option-uIndicates the specified user

[[email protected] ~]# crontab -l -u learner
no crontab for learner
[[email protected] ~]#

option-eRepresents the cron table of the editing user. When editing, the system will select the default editor, which is the default editor in the author’s environmentvi
By directly editing the file/etc/crontabYou can set the cron table at the system level.
usecrontab -eWhen editing in / tmp mode, a temporary file will be generated under / TMP and savedcrondThe content will be written to a file with the same name as the user name under / var / spool / cron,crondThe syntax will be checked when saving. This is also the recommended usage for setting scheduled tasks.

Syntax:

*  *  *  *  *  command

Each line represents a task and is represented by a symbol#The first line represents a comment and is not effective. Each part is divided into six lines, as shown in the above figure:

The first part represents minutes (0-59), * represents every minute
The second part represents hours (0-23), * represents every hour
The third part represents the day (1-31), * represents the day
The fourth part represents the month (1-12), * represents the month
The fifth part represents the day of the week (0-6,0 represents Sunday), * represents every day of the week
The sixth part indicates the tasks to be performed

In the first five parts about time setting, except*Three other symbols are supported in addition to any time of the current part/,-Respectively representevery otherTime point a and time point BTime point a to time point B
For example, test the connectivity of 10.0.1.252 every 3 minutes and output the results to / root / 252 Log

[[email protected] ~]# crontab -e
*/3 * * * * /usr/bin/ping -c1 10.0.1.252 &>> /root/252.log

After saving, there will becrontab: installing new crontabThe words appear. Note that none of the six parts can be empty. It is better to write the absolute path of the command. When editing the regular tasks of ordinary users, pay attention to the execution authority of the command.

For example, from January to may, perform backup tasks at 2:30 a.m. on Tuesday and Friday every week

30 2 * 1-5 2,5 /bin/bash /root/temp/backup.sh

Write the backup script here/root/temp/backup.shMedium execution

For example, from March to June and September to December, the refresh task is performed every 2 minutes from 12:00 to 14:00 every Monday to Friday

*/2 12-14 * 3-6,9-12 1-5 /bin/bash /root/temp/refresh.sh

Mixing date, time and special symbols can combine most of the time you want.

View scheduled tasks

[[email protected] ~]# crontab -l
*/3 * * * * /usr/bin/ping -c1 10.0.1.252 &>> /root/252.log
30 2 * 1-5 2,5 /bin/bash /root/temp/backup.sh
*/2 12-14 * 3-6,9-12 1-5 /bin/bash /root/temp/refresh.sh

option-rIndicates deleting a scheduled task

[[email protected] ~]# crontab -r
[[email protected] ~]# crontab -l
no crontab for root

usecrontabA common problem is that commands or scripts that can be executed normally on the command line cannot be executed normally when scheduled tasks are set. The reason for this is generally becausecrondCommands or scripts are set up differently from the login shellenvironment variable

[[email protected] ~]# head -3 /etc/crontab 
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
[[email protected] ~]#
[[email protected] ~]# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
[[email protected] ~]#

Here’s crond’sPATHDifferent from the value in the shell,PATHThe environment variable defines the path to search for commands when the shell executes commands. More about environment variables will be described in detail in the article on shell programming.

For system level scheduled tasks, these tasks are more important. Most Linux systems contain a series of cron related subdirectories in / etc:/etc/cron.{hourly,daily,weekly,monthly}, the files in the directory define the scripts that need to be run every hour, every day, every week and every month. The exact time to run these tasks is in the file/etc/crontabSpecified in. For example:

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

For a 24-hour server, the regular operation of these tasks ensures the stability of the server. However, it is noted that the execution of these tasks is generally in the early morning. For Linux computers (such as notebooks) that often need to be shut down, it is likely to be shut down when cron needs to be run. Cron cannot be run, and the system will slow down after a long time. For such systems, Linux introduces another toolanacronTo be responsible for performing system scheduled tasks.
anacronThe purpose of is not to completely replacecron, ascronA supplement to.anacronThe task defined in the file/etc/anacrontabMedium:

# /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

AndcronIt’s different from running as a daemon,anacronIt runs and terminates as a normal process. For each task defined,anacronAfter the system is started, the task that should be run will be checked to determine whether the time from the last run to the present exceeds the predetermined number of days (/ etc / anacrontab, the first column of the task line). If it is greater than the predetermined number of days, the task will be run after a delay of one time (/ etc / anacrontab, the second column of the task line). This ensures the implementation of the task. aboutanacronPlease refer to the relevant documents for more information.

3、systemd.timer

crondandatdServices are minute based, meaning they wake up every minute to check if there are tasks to perform. If the execution of a task needs to be accurate to seconds,crondandatdThere’s nothing I can do. Based onsystemdOn the system, you can use the timersystemd.timerTo achieve scheduled tasks accurate to seconds.
In the previous article, we mentioned the concept of service unit in SYSTEMd. Here we need to use two of them:.serviceand.timer。 among.serviceBe responsible for configuring the tasks to be run,.timerResponsible for configuring execution time.

Let’s start with an example:

Create task script

[[email protected] temp]# cat /root/temp/ping252.sh 
#!/bin/bash
ping -c1 10.0.1.252 &>> /root/temp/252.log

Configure services service

[[email protected] temp]# cd /usr/lib/systemd/system
[[email protected] system]# cat ping252.service 
[Unit]
Description=ping 252

[Service]
Type=simple
ExecStart=/root/temp/ping252.sh
[[email protected] system]# 

Configure timer timer

[[email protected] temp]# cd /usr/lib/systemd/system
[[email protected] system]# cat ping252.timer 
[Unit]
Description=ping 252 every 30s

[Timer]
# Time to wait after enable this unit
OnActiveSec=60
# Time between running each consecutive time
OnUnitActiveSec=30
Unit=ping252.service

[Install]
WantedBy=multi-user.target
[[email protected] system]# 

Enable timer

[[email protected] system]# systemctl enable ping252.timer
Created symlink from /etc/systemd/system/multi-user.target.wants/ping252.timer to /usr/lib/systemd/system/ping252.timer.
[[email protected] system]# systemctl start ping252.timer

see

#Timer
[[email protected] system]# systemctl status ping252.timer
● ping252.timer - ping 252 every 30s
   Loaded: loaded (/usr/lib/systemd/system/ping252.timer; enabled; vendor preset: disabled)
   Active: active (waiting) since V 2016-12-23 14:27:26 CST; 3min 42s ago

At 14:27:26 on December 23, centos7 system d [1]: started Ping 252 every 30s
At 14:27:26 on December 23, centos7 SYSTEMd [1]: starting Ping 252 every 30s
#Service
[[email protected] system]# systemctl status ping252
● ping252.service - ping 252
   Loaded: loaded (/usr/lib/systemd/system/ping252.service; static; vendor preset: disabled)
   Active: active (running) since V 2016-12-23 14:35:38 CST; 2ms ago
 Main PID: 11494 (ping252.sh)
   CGroup: /system.slice/ping252.service
           └─11494 /bin/bash /root/temp/ping252.sh

December 23 14:35:38 centos7 SYSTEMd [1]: started Ping 252
December 23 14:35:38 centos7 SYSTEMd [1]: starting Ping 252

Deactivate

[[email protected] system]# systemctl disable ping252.timer 
Removed symlink /etc/systemd/system/multi-user.target.wants/ping252.timer.
[[email protected] system]# systemctl stop ping252.timer
[[email protected] system]# 

After the timer is enabled for 1 minute, you will see / root / temp / 252 Log file is generated, and then the content is written every 30 seconds.systemdThe service unit configuration file of is differentlabelDivided into different configuration blocks, where:

[Unit]The general configuration information that does not depend on a specific type is specified under the tag. For example, both files in the example specify an optionDescription=Represents descriptive information.

[Install]The installation information under the label of this unit is savedWantedBy=Indicates when usingsystemctl enableWhen the command enables the cell, it will be in the specified target.wants/or.requires/Create the corresponding symbolic link under (as in the above example). The result is that when the specified target is started, the unit will also be started.

Except for the labels that can be set in all these two configuration files (other options can be set through the commandman 5 systemd.unitEach service unit also has a tag of a specific unit type, for example, in our example.serviceFiles in[Service]and.timerFiles in[Timer]

[Service]Under labelType=The value after indicates the execution mode and is set tosimpleAnd cooperateExecStart=Indicates that the specified program (the script in our example) will not be started without fork(); If set tooneshotIndicates only one execution (similar)at), if you need SYSTEMd to think that the service is still active after the service process exits, you also need to setRemainAfterExit=yes。 For other options, use the commandman 5 systemd.servicesee

[Timer]A variety of monotonic timers can be specified in the label. The so-called “monotonic time” means that from the moment of startup (zero), as long as the system is running, the time will continue to monotonically increase evenly (but the time will remain unchanged when the system is dormant), will never go back, and has nothing to do with the time zone. Even if the user modifies the system time forward / backward during the operation of the system, it will not have any impact on the “monotonous time”. include:

Onactivesec = indicates the point in time when this unit is enabled
Onbootsec = indicates the point in time when the machine is started
Onstartupsec = indicates the point in time when the system was first started relative to SYSTEMd
Onunitactivesec = indicates the time point when the matching unit (the unit specified by unit = under this label) was last started
Onunitinactivesec = indicates the last stop time relative to the matching unit (unit = specified unit under this label)

Two of them are used in our exampleOnActiveSec=60andOnUnitActiveSec=30Specifies that this unit is called 60 seconds after it is enabledUnit=After this unit is enabled, it is enabled again every 30 seconds to achieve the purpose of regular execution.

The time units specified after these timers can be: US (microseconds), MS (milliseconds), s (seconds), m (minutes), H (hours), D (days), w (weeks), month, y (years). If the unit is omitted, the default unit ‘second’ is used. Can be written as5h 30minIndicates the next 5 hours and 30 minutes.

[Timer]A calendar timer based on wall clock can also be set under the labelOnCalendar=, the so-called “wall clock time” refers to the time of the wall clock in the real world. In the operating system, it is actually the system time. This time is read from the clock chip of the motherboard when the operating system is started. Since this time can be modified manually, it is not necessarily monotonous or uniform. The time format can be:

Thu, Fri 2012 - * - 1,5 11:12:13 # refers to the 1st and 5th of any month in 2012. If it is Thursday or Friday, it will be executed at 11:12:13
*-*-**: *: 00 # means every minute
*-*-*00:00:00 # means every day
*-01,07-01 00:00:00 # means every six months
*: 0 / 15 # means every 15 minutes
12,14,13:20,10,30 # means 10, 20, 30 at 12 / 13 / 14
Mon, Fri * - 01 / 2-01,03 *: 30:45 # refers to the 1st and 3rd days of odd months in any year. If it is Monday or Friday, it will be executed in 30 minutes and 45 seconds of each hour

Other contents of monotone timer and calendar timer can be controlled by commandman 7 systemd.timequery

Unit=The following indicates the service unit associated with this timer (ping252. Service in our example).
Most of the setting options in the service unit can be specified multiple times and will take effect without conflict, such as.timerMultiple units can be set in, indicating that these service units share a timer.

in addition[Timer]Options can also be set under the labelPersistent=, it’s only forOnCalendar=The calendar timer defined by the instruction is meaningful. If set toyes(the default isno), it means that the last trigger time of the matching unit is permanently saved on the disk. In this way, when the timer unit is started again, if the matching unit should have been started at least once during the stop of the timer unit, the matching unit will be started immediately. In this way, the tasks that must be performed will not be missed due to shutdown. (similar toanacron(function of)
More options on timers can be found throughman systemd.timersee

usesystemd.timerSetting a scheduled task can be used insteadatdandcrondAll functions of, in additionsystemdIt has also taken over many other services, which are beyond the scope of this article. If relevant contents are involved in future articles, they will be introduced accordingly.