本篇博客的资源整理来自:https://blog.csdn.net/qq_32923745/article/details/78286385
crontab:在指定的时间执行一个shell脚本或者一系列Linux命令。时间间隔的单位可以是分钟、小时、日、月、周及以上的任意组合。这个命令非常设合周期性的日志分析或数据备份等工作。
1、crontab的命令参数及其功能
crontab -u user:用来设定某个用户的crontab服务,例如,“-u ixdba”表示设定ixdba用户的crontab服务,此参数一般有root用户来运行。
crontab file:file是命令文件的名字,表示将file做为crontab的任务列表文件并载入crontab。如果在命令行中没有指定这个文件,crontab命令将接受标准输入(键盘)上键入的命令,并将它们载入crontab。
crontab -e [user]:编辑某个用户的crontab文件内容。如果不指定用户,则表示编辑当前用户的crontab文件。
crontab -l [user]:显示某个用户的crontab文件内容,如果不指定用户,则表示显示当前用户的crontab文件内容。
crontab -r [user]:从/var/spool/cron目录中删除某个用户的crontab文件,如果不指定用户,则默认删除当前用户的crontab文件。
crontab -i:在删除用户的crontab文件时给确认提示。
crontab-d[user] -删除用户目前的crontab
2、crontab 文件的格式
minute hour day month week command
# 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 表示星期(0 或 7 表示星期天)
| | | | | .------------------- username 以哪个用户来执行
| | | | | | .------ command 要执行的命令,可以是系统命令,也可以是自己编写的脚本文件
| | | | | | |
* * * * * user-name command to be executed
3、crontab服务的启动与关闭
service crond status # 查看cond 状态
service crond start # 启动cron
service crond stop # 关闭cron
service crond restart # 重启cron
示例:
格式 | 说明 |
---|---|
*/1 * * * * service httpd restart |
每一分钟 重启httpd服务 |
0 */1 * * * service httpd restart |
每一小时 重启httpd服务 |
30 21 * * * service httpd restart |
每天 21:30 分 重启httpd服务 |
26 4 1,5,23,28 * * service httpd restart |
每月的1号,5号 23 号 28 号 的4点26分,重启httpd服务 |
26 4 1-21 * * service httpd restart |
每月的1号到21号 的4点26分,重启httpd服务 |
*/2 * * * * service httpd restart |
每隔两分钟 执行,偶数分钟 重启httpd服务 |
1-59/2 * * * * service httpd restart |
每隔两分钟 执行,奇数 重启httpd服务 |
0 23-7/1 * * * service httpd restart |
每天的晚上11点到早上7点 每隔一个小时 重启httpd服务 |
0,30 18-23 * * * service httpd restart |
每天18点到23点 每隔30分钟 重启httpd服务 |
0-59/30 18-23 * * * service httpd restart |
每天18点到23点 每隔30分钟 重启httpd服务 |
59 1 1-7 4 * test 'date +\%w' -eq 0 && /root/a.sh |
四月的第一个星期日 01:59 分运行脚本 /root/a.sh ,命令中的 test 是判断,%w 是数字的星期几 |
小结:
*
表示任何时候都匹配"a,b,c"
表示a 或者 b 或者c 执行命令"a-b"
表示a到b 之间 执行命令"*/a"
表示每 a分钟(小时等) 执行一次- crontab 不能编辑系统级的 任务
其他需求 : crontab 最小执行时间是分钟,如果是需要 半分钟执行,如果实现呢?,看如下:
每30秒 把时间写入 /tmp/cron.txt 文件
*/1 * * * * data >> /tmp/cron.txt
*/1 * * * * sleep 30s;data >> /tmp/cron.txt
扫描二维码关注公众号,回复:
2226095 查看本文章