1 安装
# 安装定时程序
yum -y install cronie yum-cron
# 设置定时任务自清单
systemctl enable crond
# 启动定时任务程序
systemctl start crond
2. 配置定时规则
vim /etc/crontab
# 或者 crontab -e 立即生效
2.1 指令语法:
usage: crontab [-u user] file
crontab [-u user] [ -e | -l | -r ]
(default operation is replace, per 1003.2)
-e (edit user's crontab) 编辑用户命令
-l (list user's crontab) 列表
-r (delete user's crontab) 删除用户任务
-i (prompt before deleting user's crontab) 在删除前确认
-s (selinux context)
参数 | 含义 | 指定示例 |
-l | 查看crontab文件内容,提示:l为list的缩写 | crontab -l |
-e | 编辑crontab文件内容,提示:e可为edit 的缩写 | crontab -e |
-i | 删除crontab文件内容,删除前会提示确认,用得少 | crontab -ri |
-r | 删除crontab文件内容。用得很少 | crontab -r |
-u | 指定使用的用户执行任务 | crontab -u boy -l |
特别强调:-I –r参数在生产中很少用,没什么需求必须要用-e进去编辑即可 补充:crontab {-l|-e}实际上就是在操作/var/spool/cron/当前用户这样的文件 |
2.2 crontab语法规则
通过crontab可以在固定的时间执行指定的系统指令,时间单位可以是分钟、小时、日、月、周以及以上的任意组合
#5s执行一次
*/5 * * * * /home/mysql-bak/mysql-bak.sh
特殊符号 | 含义 |
* | *号,表示任意时间都,也是”每”的意思,举例:如00 23 * * *cmd表示每月每周每日的23:00都执行cmd任务 |
- | 减号,表示分隔符,表示一个时间段范围段,如17-19点,每小时的00分执行任务,00 17-19 * * * cmd 。就是17,18,19点整点分别执行的意思 |
, | 逗号,表示分隔时段的意思,30 17,18,19 * * * /bin.sh /scripts/dingjian.sh表示每天17,18和19点的半点时刻执行/scripts/dingjian.sh脚本。也可以和”-”结合使用,如:30 3-5,17-19 * * * /scripts/dingjian.sh |
/n | N代表数字,即”每隔n单位时间”,如:每10分钟执行一次任务可以写成 */10 * * * * cmd,其中“*/10”的范围是0-59,因此也可以写成0-59/10 |
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# 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
0 1 * * * root /home/programs/cron/scan_bak.sh
3 保存生效
crontab /etc/crontab
4 查看任务
crontab -l