简介
作用
计划任务主要是做一些周期性的任务,
目前最主要的用途是定期备份数据。
分类
一次性调度执行 at
循环调度执行 cron
接下来我们进行详细的了解
一次性调度执行
语法格式
at
示例
now +5min #5分钟后
teatime tomorrow(teatime is 16:00) #下午茶时间
noon +4 days #第四天中午
5pm august 3 2029 #2029年8月3日下午五点
实例1
#设置一个定时创建用户的任务
[root@localhost ~]# at now +1min
at> useradd uuuu
at> <EOT> #CTRL+D输入完毕,提交任务
job 1 at Sat Mar 21 22:34:00 2019
#查询任务
[root@localhost ~]# atq
3 Thu Mar 30 09:55:00 2019 a root
#验证结果
[root@localhost ~]# id uuuu
查出用户信息即可
循环调度执行
简介
- cron的概念和crontab是不可分割的。
- crontab是一个命令,常见于Unix和Linux的操作系统之中用于设置周期性被执行的指令。
- 该命令从标准输入设备读取指令,并将其存放于“/etc/crontab”文件中,以供之后读取和执行。
查看进程状态
[root@qianfeng ~]# systemctl status crond.service
[root@qianfeng ~]# ps aux |grep crond
root 550 0.0 0.0 126300 1648 ? Ss 10:05 0:00 /usr/sbin/crond -n
crond程序运行是计划任务执行的根本
cron实例
管理方式
- 创建任务
"crontab -e" Edit jobs for the current user
- 查询任务
"crontab -e" Edit jobs for the current user
管理员可以使用 -u username, 去管理其他用户的计划任务
- 删除任务
"crontab -e" Edit jobs for the current user
计划任务储存位置
[root@localhost ~]# ls /var/spool/cron/
语法格式job format
# .---------------- 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
# | | | | |
# * * * * * command
# 分时日月周 命令或脚本
#以上六个部分用空格隔开
实例
0 * * * * /mysql_back.sh -------每小时的0分执行
*/5 * * * * /mysql_back.sh ------每五分钟执行
0 2 1,4,6 * * /mysql_back.sh ------每月的1,4,6日的2点整执行
0 2 5-9 * * /mysql_back.sh --------每月5日到9日的两点整执行
0 2 * * 5 /mysql_back.sh ---------不写月日,仅周生效----每月的周五两点执行
0 2 2 6 5 /mysql_back.sh -------书写月和日,月或日,月日周均生效 ----6月2日的两点整执行--------6月的周五两点整执行
实例操作:
#创建每分钟创建文件的计划任务
[root@localhost ~]# touch write.sh
[root@localhost ~]# vim write.sh
#!/bin/bash
time=$(date "+%Y-%m-%d-%H:%M:%S") ##获取当前时间并且格式化时间
cd /tmp/kk ##切换到这个目录下
mkdir "${time}" ##创建以时间命名的文件夹
:wq
#赋予权限
[root@localhost ~]# chmod +x write.sh
[root@localhost ~]# crontab -e
crontab: installing new crontab
#查看目录
[root@localhost ~]# ls -l /tmp/kk
总用量 0
drwxr-xr-x. 2 root root 6 8月 5 20:12 2020-08-05-20:12:01
drwxr-xr-x. 2 root root 6 8月 5 20:13 2020-08-05-20:13:01
drwxrwxr-x+ 2 root root 73 8月 5 17:29 wangruikang
#成功