您的位置:首页 > 运维架构 > Shell

linux下shell执行秒级计划任务

2013-04-03 19:41 441 查看
【方案一】

#!/bin/bash
#执行出队
url="http://localhost/redis/push/redis_pop.php";
CURL=$(which curl)
while true
do
#$CURL $url
#$CURL $url >> /usr/local/apache2/htdocs/redis/push/push.log 2>&1
sleep 2
done

【方案二】

crontab是linux自带的计划任务程序,可以实现分,时,日,周,月。

但是crontab有两个缺陷:
1.最小粒度为分,对于秒不支持
2.若是上一个任务的执行时间超过下一个任务的开始时间的话,就会出现两个任务并行的现象,这样任务会越积越多,最后系统挂了。
这周在项目里需要实现每隔10秒去执行任务的功能,因此写了个shell程序:
1.可以自定义程序执行时间间隔,
2.使用的是deamon方式,产生两个进程,父进程监控子进程,若是子进程挂了,父进程重新启动子进程,子进程负责每隔10秒钟执行任务;
3.而且当任务执行时间超长时,不会出现两个任务同时执行的现象,下一个任务只会延后。也可以用后台运行方式运行任务,这样和crontab的效果一样
4.若是时间间隔为10秒,而任务只执行了1秒,则sleep 9秒后,执行下一次任务
5.若是把sleep改为usleep的话可以精确到微秒

#运行执行 sh /Application/sdns/trigger/task_crontab.sh >> /Application/sdns/log/crontab.log 2>&1

#要定时执行的脚本,注意:不使用后台运行,则若是超过10秒的话,下一次会延迟,若是使用后台执行的话,有可能出现两个任务并行的问题

dlc_cmdline="sh /Application/sdns/trigger/dotask.sh >> /Application/sdns/log/dotask.log";

#本shell脚本的执行路径

dlc_thiscmd="sh /Application/sdns/trigger/task_crontab.sh >> /Application/sdns/log/crontab.log 2>&1"

#任务执行时间间隔

dlc_task_timeout=10;

#是否后台执行deamon

is_deamon=$1;

#deamon,父进程

if [ "$is_deamon" == "--deamon" ]

then

echo "deamon start"

while [ 1 ]

do

date +"%F %T $dlc_thiscmd is started";

#调用子进程

$dlc_thiscmd

date +"%F %T $dlc_thiscmd is ended";

done

fi

#子进程的代码

while [ 1 ]

do

date +"%F %T $dlc_cmdline is started" ;

#记录本次程序开始时间

dlc_start_time=`date +%s`

#执行任务

$dlc_cmdline

#计算和时间间隔的差距

dlc_sleep_time=$(($dlc_task_timeout+$dlc_start_time-`date +%s`));

echo "sleep_time=[$dlc_sleep_time]";

#不够10秒,则sleep到10秒

if [ "$dlc_sleep_time" -gt 0 ]

then

sleep $dlc_sleep_time;

fi

date +"%F %T $dlc_cmdline is ended";

done
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: