centos中预装有crontab定时任务工具,我们可以用来定时执行一些shell脚本,比如清理服务器,晚上执行sonar分享等各种场景使用
常用命令
// 在 /etc/crontab 文件写入定时任务shell脚本
vi /etc/crontab
// 在 crontab 文件第二行 PATH 添加 /usr/local/bin 目录
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
// 最后一句加入,早上9点40用root执行etcsonar.sh 脚本,并写入日志文件logetc.txt
40 9 * * * root cd /root/sonargit && /bin/sh -x etcsonar.sh >/root/sonargit/logetc.txt 2>&1
// 修改/root/sonargit/etcsonar.sh可执行权限
chmod -x /root/sonargit/etcsonar.sh
// 加载定时任务生效
crontab /etc/crontab
// 查看哪些定时任务
crontab -l
// 实时查看定时任务执行日志
tail -f /var/log/cron
坑-PATH变量
默认crontab中PATH环境变量和系统PATH环境变量不同,这里可以查看 /etc/crontab
内容,可以看到第二行PATH没有常用的/usr/local/bin
目录,因为我们通常环境变量目录有 /usr/bin
和 /usr/local/bin
,所以会导致如果这里执行的定时任务shell脚本中含有从 /usr/local/bin
中的可执行文件,就会导致脚本执行不成功
- 做法是修改第二句为
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
,可根据自身需要环境变量增加路径
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
坑-日志输出
crontab执行定时任务看不到是否有执行,是否成功失败等日志,这个怎么做呢?
- 看是否执行日志
里面可以看到自己的任务已经是否被调用
tail -f /var/log/cron
- 看脚本日志是否成功
在 /etc/crontab
文件中加入如下定时任务,最后的 >>/root/sonargit/logetc.txt 2>&1
这句就是将脚本输出写到日志文件,就能看到过程了
// 早上9点40用root执行/root/sonargit/etcsonar.sh 脚本,并写入日志到 /root/sonargit/logetc.txt 文件
40 9 * * * root cd /root/sonargit && /bin/sh -x etcsonar.sh >/root/sonargit/logetc.txt 2>&1
坑-可执行权限
当脚本缺少可执行权限时,crontab任务无法调度执行,时表现出的现象就是脚本没有按照设置的定时参数执行,看起来就像是定时参数设置不正确似的。 注意: 这个问题很有迷惑性,会让人觉得是定时参数设置不正确,所以在使用crontab任务调度脚本执行时,首先要做的事情就是给脚本添加可执行权限。
ls -l
-rw-r--r-- 1 root root 96 Jul 28 17:12 etcsonar.sh
添加可执行权限
chmod +x task_test.sh
ls -l
-rwxr-xr-x 1 root root 96 Jul 28 17:12 etcsonar.sh
附录
/etc/crontab
文件内容
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/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
30 2 * * * root cd /root/sonargit && /bin/sh -x etcsonar.sh >>/root/sonargit/logetc.txt 2>&1
etcsonar.sh
文件内容
#!/bin/bash
cd /root/sonargit/v2coding-yunwei-chuanyi
git pull http://xxxx.com:8880/private/front/v2coding-yunwei.git
cd /root/sonargit/v2coding-yunwei/v2coding-yunwei-webapp
sonar-scanner
cd /root/sonargit/v2coding-yunwei/v2coding-yunwei-mobile
sonar-scanner