什么是crontab
crontab是linux操作系统下系统级别的定时完成任务计划的工具,类型于windows的计划任务,不过它只是命令行的。从crontab延展,java等其他语言,也大量使用了crontab的语法进行按时完成任务。
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
格式示例
*/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
三、crontab 的配置文件
文件 说明
/etc/crontab 全局配置文件
/etc/cron.d 这个目录用来存放任何要执行的crontab文件或脚本
/etc/cron.deny 该文件中所列用户不允许使用crontab命令
/etc/cron.allow 该文件中所列用户允许使用crontab命令
/var/spool/cron/ 所有用户crontab文件存放的目录,以用户名命名,比如你是root 用户,那么当你添加任务是,就会在该路径下有一个root文件。
/etc/cron.deny 该文件中所列用户不允许使用crontab命令
/var/log/cron crontab 的日志文件