引语:我本人以前并没有写过shell脚本,也许是因为懒,也许是没有被逼到要去写shell的地步。但是,前段时间,工作需求,要求重新跑几个月的脚本,这些脚本是每天定时进行跑的,而且每天是好几个脚本一起关联跑的。你也许会说,这太简单了,写个循环,然后,让他自己去跑就行了。是的,你可以很顺手的用你的编程语言去写循环,如PHP。但是,你知道,这样做其实是改变了代码结构了,鬼知道会导致什么结果呢? 并且,我并不保证里面所有代码的意思,我都懂!那么,问题来了,在不改变原代码的前提下,怎样去循环这几个月的时间呢? 没错,那就是,模拟真实运行时的情况,传入需要接收的日期参数(前提是你的代码里面已经有了这个门)!你知道,这种定时脚本都有一个优雅的名字,crontab,那么,就是shell了,你要做的就是写shell了。
没有写过shell? 没关系了,其实需求确定之后,你显然已经知道,这太简单了。不就是语法问题吗? 你别告诉我你不会谷歌,不会百度!
我就先抛几个需要考虑的点,后面直接给代码吧!
1、怎样获取当前时间,并转换成你需要的格式? 关键词: date
2、怎样防止同时多次运行同一个内容? 关键词: lock
3、怎样让程序运行完一次之后,冷却执行? 关键词: sleep
4、怎样指定运行时间段,counter或者起始日期? 关键词: while, let, expr
5、附加:怎样知道当前的运行状态如何了? 关键词: echo , progress
把这些问题考虑好了,你就一步步去写吧,不知道语法的,直接谷歌、百度,代码参考如下:
#/bin/bash
# @author: youge
# @date: 2015-12-22
startDate="2015-11-24" # when to start
startDateTimestamp=`date -d "$startDate" +%s`
endDate="2015-12-14" # when to end
endDateTimestamp=`date -d "$endDate" +%s`
sleepTime=25 # to take a break
haveSthUndo=0 # check if there is something undo , if not , exit the program
rootDir='/cygdrive/d/wamp/ppi/'
dir=$rootDir"cron/"
itemArr=("itemA" "itemB" "itemC") # the items you want to run there
for item in ${itemArr[@]}
do
runFile=$rootDir$item".run";
if [ ! -f "$runFile" ] ; then
haveSthUndo=1;
echo $item" runs on me" $runFile " touched";
echo -e "script startTime: "`date "+%Y-%m-%d %H:%M:%S"` "nbeginDate:" $startDate "nendDate:" $endDate "npath:" $dir >> $runFile
touch "$runFile";
break;
else
echo $item "is runing, skipped. " $runFile;
fi
done;
if [ $haveSthUndo -ne 1 ]; then
echo -e "Nothing to do now ...ncheck it...";
exit;
fi
echo "haveSthUndo eq: " $haveSthUndo;
while [[ $endDateTimestamp -ge $startDateTimestamp ]]
do
runDate=`date -d @$startDateTimestamp +%Y-%m-%d`; #1987-01-06
params="item=$item&d=$runDate";
msg="[`date "+%Y-%m-%d %H:%M:%S"`] now we run the date: "${runDate}" [params]: "${params};
echo $msg; # to show me ...
echo $msg >> $runFile;
# run the scripts below
cd $dir &&
/bin/php ./script1.php $params &&
/bin/php ./script2.php $params &&
/bin/php ./scriptx.php $params
# run the scripts upon
startDateTimestamp=`expr $startDateTimestamp + 86400`; # run the next day ...
echo " ___sleeping for $sleepTime seconds ... ";
x='';
for ((itime=0; itime<$sleepTime; itime++)); do
let itime2=$itime+1;
progress=`expr $itime2 * 100 / $sleepTime`;
printf "cooling:[%-"$sleepTime"s]%d%%r" $x $progress
x=#$x
sleep 1; # sleep xx seconds to run the next time, show the progress
done;
echo;
done;
echo "[`date "+%Y-%m-%d %H:%M:%S"`] the end." >> $runFile;
#end of the file










