Linux uses systemd service and crontab to realize automatic running of Shell scripts at boot & edit the crontab content of the current user or specified user crontab -e

Introduction

systemd is an initialization system and service manager in the Linux system. It can be used to automatically run shell scripts on system startup.
crontab is a tool for executing tasks regularly. We can set up automatic startup by editing the crontab file

Prerequisites

Create a Shell script file, such as myscript.sh. This script will run automatically when the system starts.
Move the script file to a suitable directory, such as /path/to/myscript.sh.

Use systemd service

Create a .service file

[Unit]
Description=My Script Service
After=network.target

[Service]
ExecStart=/path/to/myscript.sh

[Install]
WantedBy=default.target

Move the .service file to the /etc/systemd/system/ directory.

Detailed explanation of service file content

[Unit]
Description=My Script Service
After=network.target

Description:描述服务的简短说明
After:指定了服务应该在哪个目标(target)之后启动,在这里是"network.target",则服务需要在网络启动之后才能正常运行

[Service]
ExecStart=/path/to/myscript.sh
ExecStart:指定了服务启动时的执行命令或脚本的路径

[Install]
WantedBy=default.target
WantedBy:指定了服务应该被关联到哪个目标(target)进行启动,默认为"default.target",意味着服务会随系统的默认目标一起启动。
1234567891011121314
#刷新systemd服务:
sudo systemctl daemon-reload

#使用以下命令来启用服务并使其在系统启动时自动运行:
sudo systemctl enable myscript.service

#使用以下命令手动启动服务:
sudo systemctl start myscript.service

Note: If you start the service manually at this time, it will run immediately. However, after the system restarts, the service will start automatically.

Use crontab

Open a terminal and enter the following command to edit the crontab file:

crontab -e
#在打开的文件中添加以下内容:

@reboot /path/to/myscript.sh
#/path/to/myscript.sh是你的Shell脚本文件的路径

Save and exit the editor.



crontab for linux scheduled tasks

The crond service provides two ways to set scheduled tasks, one is a system scheduled task, and the other is a regular user's scheduled task. System scheduled tasks are set by the system administrator by writing the /etc/crontab configuration file, and the crontab tasks are stored in the /etc/crontab file. Regular users' scheduled tasks can be written by the current user using crontab -e. The written scheduled tasks are stored in the /var/spool/cron/$USER file.

crontab depends on crond service
service crond status
chkconfig --list|grep crond
The software package is provided by crontabs-1.10-33.el6.noarch provides
rpm -qa|grep crontab

The crond service will check the contents of /etc/crontab and /var/spool/cron/$USER files every 1 minute. If new ones are found, it will reload the changed files into memory (this will appear in the cron log (system) RELOAD (/etc/crontab)), if you want faster execution after modifying the configuration file, you can restart the crond service through Checked the /var/log/cron log and found that it could be sped up by a few seconds.

Sep  2 10:54:25 centos6 crond[4050]: (CRON) STARTUP (1.4.4)
Sep  2 10:54:26 centos6 crond[4050]: (CRON) INFO (running with inotify support)
Sep  2 10:54:26 centos6 crond[4050]: (CRON) INFO (@reboot jobs will be run at computer's startup.)
Sep  2 10:55:02 centos6 CROND[4060]: (root) CMD (sh /tmp/test.sh)

Sep  2 10:56:01 centos6 crond[4050]: (*system*) RELOAD (/etc/crontab)

The administrator writes system routine tasks
vim /etc/crontab
In this configuration file, the user who executes the command needs to be specified, and in Crontab -e is not needed, because crontab -e is the currently logged in user to execute the command.
SHELL and PATH variables define where to search for commands in this configuration file if the absolute path is not written. Therefore, it is generally recommended to write the absolute path for execution.
MAILTO is used to send the errors and errors that occur during the execution of the following scheduled tasks to the user's mailbox. Of course, they will also be recorded in the /var/log/cron log.

There are two ways to write :
1. Specify the timing interval and write the execution command. It is recommended to specify the execution user here
For example, root prints the time every 1 minute and sends it to the /tmp/time.txt file

*/1 * * * * root date>>/tmp/time.txt

2, Run all shell scripts in the specified directory through the run-parts command. This can only be configured in /etc/crontab and cannot be configured in crontab -e< /span>
For example, let the root user execute all scripts in the test_sh directory at 3:50 every day

(1)创建test_sh目录
mkdir -p /tmp/test_sh
(2)将shell脚本存放在test_sh目录里
shell脚本必须具有执行权限
chmod u+x *
(3)编写定时任务
50 03 * * * root run-parts /tmp/test_sh

The system's default directory for storing shell scripts

[root@centos6 ~]# ls -ld /etc/cron*ly
drwxr-xr-x. 2 root root 4096 Sep 27  2011 /etc/cron.daily
drwxr-xr-x. 2 root root 4096 Sep 27  2011 /etc/cron.hourly
drwxr-xr-x. 2 root root 4096 Sep 27  2011 /etc/cron.monthly
drwxr-xr-x. 2 root root 4096 Sep 27  2011 /etc/cron.weekly
[root@centos6 ~]# 
比如每小时执行一次的任务,可以将脚本放在/etc/cron.hourly目录下
编写/etc/crontab,定在每小时15分执行
15 * * * * root run-parts /etc/cron.hourly

crontab configuration file (format description)

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# 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

Common user timing configuration examples:

说明:
*代表该列每个合法值
%代表换行,如果在crontab中某些命令涉及使用%,比如date命令,那么需要将%进行转义
,代表多个值,每个值用,分割开
a-b代表从某个区间范围,是闭区间。如“2-5”表示“2,3,4,5”
a/b 代表从a值开始,每隔b值执行一次。比如在分钟列上,2/47,从2分钟开始,每隔47分钟执行一次,也就是2,49,2...执行后续命令

Write multiple commands in crontab

*/2 * * * * date >/tmp/test3.log;/bin/date +'\%Y-\%m-\%d \%H:\%M:\%S'>>/tmp/test3.log
*/2 * * * * date >/tmp/test3.log && /bin/date +'\%Y-\%m-\%d \%H:\%M:\%S'>>/tmp/test3.log
*/2 * * * * date >/tmp/test3.log||/bin/date +'\%Y-\%m-\%d \%H:\%M:\%S'>>/tmp/test3.log

Common command execution interval settings

格式设置中,都是将条件进行求并集的关系

每一分钟执行一次command
* * * * * cmd
每小时的15,30,45,00执行一次命令
00,15,30,45 * * * * cmd
每天10:15,10:30,10:45执行该命令
15,30,45 10 * * * cmd
每天上午8-11点的第3和15分钟执行
3,15 8-11 * * * cmd
每隔2天的上午8-11点的第3和15分钟执行
3,15 8-11 */2 * * cmd
每个星期一的上午8点到11点的第3和第15分钟执行
3,15 8-11 * * 1 cmd
每月1、10、22日的4 : 45
45 4 1,10,22 * * cmd
每周六、周日的1 : 10
10 1 * * 6,0 cmd
每天18 : 00至23 : 00之间每隔30分钟
0,30 18-23 * * * cmd
晚上11点到早上7点之间,每隔1小时执行一次
* 23-07/1 * * * cmd
每月的4号与每周一到周三的11点【这里是取两个条件的并集,这个很重要】
00 11 4 * 1-3 cmd 

其他注意事项:
尽量不要将任务放在同一时间执行。

In crond, the minimum timing unit is minutes. To implement execution every few seconds, you must use a script to achieve it.

每隔2秒执行一次命令
* * * * *  sh test.sh
#!/bin/bash
step=2 
for (( i = 0; i < 60; i=(i+step) )); do  
   date +'%Y-%m-%d %H:%M:%S'>>/tmp/oracle.txt ;  
   sleep $step  
done  
exit 0  

每隔50秒执行一次命令
50秒均分多少分钟,而1分钟是60秒,那就是50和60的最小公倍数是300秒也就是5分钟。

*/5 * * * *  sh test.sh
#!/bin/bash
step=50 
for (( i = 0; i < 300; i=(i+step) )); do  
   date +'%Y-%m-%d %H:%M:%S'>>/tmp/oracle.txt ;  
      sleep $step  
done       
exit 0    


每隔90分钟执行一次
90分钟能均分多少小时,也就是90分钟和60分钟的最小公倍数180,也就是3个小时,那就每隔3个小时执行一次,而3个小时也能均分一天24小时,这3个小时内由90分钟均分。

* */3 * * *  sh test.sh
#!/bin/bash
step=5400 
for (( i = 0; i < 10800; i=(i+step) )); do  
   date +'%Y-%m-%d %H:%M:%S'>>/tmp/oracle.txt ;  
      sleep $step  
done       
exit 0    

Modify the current user's crontab content
crontab -e actually modifies the current user's crontab content. The file is the content in /var/spool/cron/$USER

After the modification is completed, restart the crond service and execute the crontab content after a few seconds of delay. Otherwise, the Linux cron service will read /var/spool/cron, /etc/crontab, /etc/cron.d every one minute.

Aug 29 16:16:48 dg1 crond[24132]: (CRON) STARTUP (1.4.4)
Aug 29 16:16:50 dg1 crond[24132]: (CRON) INFO (running with inotify support)
Aug 29 16:16:50 dg1 crond[24132]: (CRON) INFO (@reboot jobs will be run at computer's startup.)
.
.
.

Aug 29 16:17:01 dg1 CROND[24138]: (root) CMD (su - oracle -c  /home/oracle/test/test.sh 1>1.log 2>&1)
Aug 29 16:17:01 dg1 CROND[24139]: (root) CMD (root (/usr/sbin/ntpdate 1.cn.pool.ntp.org && /sbin/hwclock -w) &>/dev/null)

Modify the system's crontab content and set it in /etc/crontab

Users in /etc/cron.deny are not allowed to execute crontab content

The scripts in /etc/cron.daily, /etc/cron.hourly, /etc/cron.monthly these directories are scripts to be executed every day, every hour, and every month.

The files under /etc/cron.d/ are the scheduled crontab contents of the system configuration.

Usage of crontab command:
1. View the crontab tasks of the current user
crontab -l
crontab - u oracle -l
2. Delete the current user's crontab content
crontab -ri
crontab -u oracle -ri crontab -u oracle -e crontab -e
3. Edit the crontab content of the current user or the specified user

Guess you like

Origin blog.csdn.net/qq_43842093/article/details/135032360