wncuicui 发表于 2013-2-7 00:48:31

crontab陷阱

工作中常用crontab来执行一些定时任务,带来了很大的方便的同时,也遇到过一些问题,耗费了不少时间查找错误。现在写出来供大家参考一下。
 
http://www.agoit.com/images/smiles/icon_smile.gif系统后台定时任务比较多,需要不同的任务错开时间运行,可以参考
# m h dom mon dow  command
17-23/3 * * * * sh task1.sh  #task1在17,20,23分钟运行
18-24/3 * * * * sh task2.sh  #task2在18,21,24分钟运行
19-25/3 * * * * sh task3.sh  #task3在19,22,25分钟运行
 
http://www.agoit.com/images/smiles/icon_smile.gifcrontab命令执行时的当前目录是/root,若要执行/workbench/traffic-alert/detect.php文件,而且执行时当前目录要求为项目根目录,有以下两种写法
1. */5 * * * * cd /workbench/traffic-alert/ && php detect.php
这种方法不够优雅,容易直接写成php /workbench/traffic-alert/detect.php
2. */5 * * * * sh /workbench/traffic-alert/start.sh
# File : start.sh
MY_HOME=`dirname $0`
cd $MY_HOME
php detect.php
这样不管将/traffic-alert目录拷贝到何处,只要在crontab中写入sh /anywhere/traffic-alert/start.sh即可。
 
http://www.agoit.com/images/smiles/icon_sad.gifcrontab命令项中不能直接写百分号(%),需要加上反斜杠(\)转义
一次测试中,在终端下运行 sh start.sh `date +'%Y %m %d' -d -1day`可以得到正确结果,而在crontab中却失败,纠结了一个晚上最后才查到正确的写法应该是 sh start.sh `date +'\%Y \%m \%d' -d -1day`
 
http://www.agoit.com/images/smiles/icon_cry.gif这次是最郁闷的,先来两张图片

http://dl.iteye.com/upload/attachment/346758/bd330ac6-da4b-31dc-95fe-949a54fb6b51.png

http://dl.iteye.com/upload/attachment/346760/2a94ff05-ad3a-33ed-867d-0bc8fc699327.png
 
第一张图片是在终端下执行gnuplot test_gnuplot.plt生成的,第二张是在crontab中执行生成的。相同的命令,相同的命令文件,相同的数据文件,却产生出不同的图片,折腾了一个下午后才发现,
 
系统上装了两套gnuplot,分别是,
TJSJHL242-124:/usr/share/php/renren-sendmail# /usr/local/bin/gnuplot --version
gnuplot 4.2 patchlevel 6
TJSJHL242-124:/usr/share/php/renren-sendmail# /usr/bin/gnuplot --version
gnuplot 4.2 patchlevel 2
 
终端下PATH变量为 /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
crontab执行环境下PATH变量设置为 /usr/bin:/bin
 
真相大白! 感叹gnuplot相同版本生成的图片居然差别这么大,这patch打的。。。
页: [1]
查看完整版本: crontab陷阱