Linux Crontab 计划任务
0x01 配置文件路径
系统配置文件路径
/etc/crontab
需要在五个后面加上用户,格式:/1 root ls />>/opt/crontab-e 2>&1
系统用户配置文件路径
/var/spool/cron
root:/var/spool/cron/root
user1:/var/spool/cron/user1
这个目录是以账号来区分每个用户自己的执行计划,格式:/1 * ls />>/opt/crontab-e 2>&1
0x02 命令详解
crontab [ -u user ] file 或 crontab [ -u user ] { -l | -r | -e }
-u :是指设定指定 user 的时程表
-e : 执行文字编辑器来设定时程表,内定的文字编辑器是 VI,如果你想用别的文字编辑器,则请先设定 VISUAL 环境变数来指定使用那个文字编辑器(比如说 setenv VISUAL joe)
-r : 删除目前的时程表
-l : 列出目前的时程表
0x03 检查计划任务
systemctl status crond
crontab -l
tail -f /var/log/cron
0x04 实例
例1:需要在1月2日25分执行ps aux > ps001.txt任务怎么表示? 25 * 2 1 * ps aux > ps001.txt 由于没表示小时,所以就只能设置为每小时 例2:需要跑在每周日,每分钟执行ping www.baidu.com这个命令,时间怎么表示? */1 * * * 0 ping www.baidu.com */表示每多少分钟执行一次 例3:每晚的21:30重启apache。 30 21 * * * /usr/local/etc/rc.d/lighttpd restart 例4:每月的1、10、22日的4 : 45重启 apache 45 4 1,10,22 * * /usr/local/etc/rc.d/lighttpd restart 例5:每周六、周日的 1 : 10 重启 apache 10 1 * * 6,0 /usr/local/etc/rc.d/lighttpd restart 例6:在每天18 : 00至23 : 00之间每隔30分钟重启apache 0,30 18-23 * * * /usr/local/etc/rc.d/lighttpd restart 例7:每一小时重启 apache * */1 * * * /usr/local/etc/rc.d/lighttpd restart 例8:晚上 11 点到早上 7 点之间,每隔一小时重启 apache * 23-7/1 * * * /usr/local/etc/rc.d/lighttpd restart 例9:每月的 4 号与每周一到周三的 11 点重启 apache 0 11 4 * mon-wed /usr/local/etc/rc.d/lighttpd restart 例10:一月一号的 4 点重启 apache 0 4 1 jan * /usr/local/etc/rc.d/lighttpd restart 例11:在 12 月内, 每天的早上 6 点到 12 点中,每隔 3 个小时执行一次 /usr/bin/backup 0 6-12/3 * 12 * /usr/bin/backup 例12:每月每天的午夜 0 点 20 分, 2 点 20 分, 4 点 20 分....执行 yum -y update 20 0-23/2 * * * yum -y update
0x10 相关链接
在线模拟解析Crontab表达式执行时间 https://tooltt.com/crontab-parse/
在线定时任务表达式在线生成 https://tooltt.com/quartzcron/