Linux之crontab设置定时任务
前言:
crontab是linux的定时任务,可以设置某个时间执行某条命令或者脚本。
crontab语法:
[root@MyServer test]# cat /etc/crontab
内容如下
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
1.crontab 定时规则:*****
- 第一个*:分钟,从0–59之间的整数
- 第二个*:小时,从0–23之间的整数
- 第三个*:日期,从1–31之间的整数
- 第四个*:月份,从1–12之间的整数
- 第五个*:周期,从1–7之间的整数
2.特殊字符:
- “*”:表示任何时刻
- “,”:表示分割
- “-”:表示间隔,如1-7,表示1到7
- “/n”:表示每n执行一次
3.crontab参数说明:
- crontab -e:执行文字编辑器来设定时程表
- crontab -r:删除目前的时程表
- crontab -l:列出当前的时程表
- crontab -v:列出cron作业的状态
4.编辑一个定时任务:
[root@MyServer test]# crontab -e
* * * * * date >> /tmp/test.log
查看输出内容
[root@MyServer test]# cat /tmp/test.log
Thu Oct 29 19:45:01 CST 2020
Thu Oct 29 19:46:01 CST 2020
Thu Oct 29 19:47:01 CST 2020
Thu Oct 29 19:48:01 CST 2020
Thu Oct 29 19:49:01 CST 2020
Thu Oct 29 19:50:01 CST 2020
Thu Oct 29 19:51:01 CST 2020
5. 删除定时任务:
[root@MyServer test]# crontab -r
6.查看contab执行的历史:
[root@MyServer test]# tail -10 /var/log/cron
Oct 29 19:46:01 MyServer CROND[30819]: (root) CMD (date >> /tmp/test.log)
Oct 29 19:47:01 MyServer CROND[30850]: (root) CMD (date >> /tmp/test.log)
Oct 29 19:48:01 MyServer CROND[30878]: (root) CMD (date >> /tmp/test.log)
Oct 29 19:49:01 MyServer CROND[30909]: (root) CMD (date >> /tmp/test.log)
Oct 29 19:50:01 MyServer CROND[30943]: (root) CMD (date >> /tmp/test.log)
Oct 29 19:50:01 MyServer CROND[30944]: (root) CMD (/usr/lib64/sa/sa1 1 1)
Oct 29 19:50:01 MyServer CROND[30942]: (root) CMD ( /home/staragent/bin/sa_recovery.sh)
Oct 29 19:50:01 MyServer CROND[30939]: (root) MAIL (mailed 56 bytes of output but got status 0x004b#012)
Oct 29 19:51:01 MyServer CROND[31022]: (root) CMD (date >> /tmp/test.log)
Oct 29 19:51:56 MyServer crontab[31050]: (root) DELETE (root)
7.常用定时任务:
- */1 * * * *:每1分钟执行一次
- 15,20,30 * * * *:每小时的第15,20,30分钟执行
- */1 * * *:每1个小时执行一次
- 20 * * 1,3,5:每周1,3,5 晚上八点执行
- 3,15 8-11 */2 * *:每隔两天的上午8点到11点的第3和第15分钟执行
总结:
以上就是crontab定时任务的一些用法,脚本的话只需要将路径脚本加入定时任务即可。
不积跬步,无以至千里;不积小流,无以成江海。
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_37668015/article/details/109332757