一、什么是计划任务
在Linux操作系统中,除了用户即时执行的命令操作以外,还可以配置在指定的时间、指定的日期执行预先计划好的系统管理任务(如定期备份、定期采集监测数据)。
计划任务分为一次性和循环性的计划任务。
二、一次调度执行——at
1.作用
at任务主要是做一些周期性的任务,目前最主要的用途是定期备份数据 。
2.语法
at <时间规格>
- now +5min
- teatime (teatime is 16:00) tomorrow midnight noon
- 5pm august 3 2024
3.使用
1)安装at
[root@master ~]# yum -y install at
[root@master ~]# systemctl start atd #首先要启动服务
[root@master ~]# systemctl status atd #查看启动状态
[root@master ~]# systemctl enable atd #做开机启动
2)创建定时任务
[root@master ~]# at now +1min
at> useradd uuuu
at> <EOT> #使用CTRL+D
[root@master ~]# atq #查看一次性任务
[root@master ~]# atrm id #删除一次性任务
3)第二种方法创建定时任务
[root@master ~]# vim at.jobs
useradd u99
useradd u00
touch /a.txt
[root@master ~]# at 20:33 < at.jobs
三、循环性的计划任务——ctontab
1.语法
Minutes Hours Day-of-Month Month Day-of-Week Command
分钟 小时 日 月 周 执行的命令,最好是命令的绝对路径
0-59 0-23 1-31 1-12 0-7时间:
*:每
*/5: 每隔5分钟
,:不同的时间段
- : 表示范围
2.管理方式
crontab -l List the jobs for the current user. //列出当前用户的计划任务
crontab -r Remove all jobs for the current users. //删除当前用户所有的计划任务
crontab -e Edit jobs for the current user. //编辑当前用户的计划任务
管理员可以使用 -u -l -e username, 去管理其他用户的计划任务
3.使用crontab
1)安装crontab
[root@master ~]# yum -y install crontabs
[root@master ~]# systemctl start crond.service
[root@master ~]# systemctl status crond.service
[root@master ~]# systemctl enable crond.service
2)创建定时任务
[root@master ~]# vim /home/soso.sh
#!/bin/bash
touch /opt/a.txt
[root@master ~]# chmod +x /home/soso.sh
每天6:00执行
0 6 * * * /home/soso.sh
每天8:40执行
40 8 * * * /home/soso.sh
每周六凌晨4:00执行
0 4 * * 6 /home/soso.sh
每周六凌晨4:05执行
5 4 * * 6 /home/soso.sh
每周六凌晨5:00执行
0 5 * * 6 /home/soso.sh
每周一到周五9:30
30 9 * * 1-5 /home/soso.sh
每周一到周五8:00,每周一到周五9:00
0 8,9 * * 1-5 /home/soso.sh
每周六23:59
59 23 * * 6 /home/soso.sh
每天0:30
30 0 * * * /home/soso.sh
每年2月的3日和周五的15:22执行
22 15 3 2 5 /home/soso.sh 每年2月的3日和周五的15:22执行
3)crontab文件的作用
1.使用者权限文件:
文件:
/etc/cron.deny
说明:
该文件中所列用户不允许使用crontab命令文件:
/etc/cron.allow
# 当这个文件产生时,/etc/cron.deny文件失去作用,只有这个文件中的用户才能使用crontab
说明:
该文件中所列用户允许使用crontab命令2.系统本身的计划任务
/etc/crontab