<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<title><![CDATA[静怡家园]]></title> 
<link>http://www.zhanghaijun.com/index.php</link> 
<description><![CDATA[书山有路勤为径，学海无涯苦作舟！]]></description> 
<language>zh-cn</language> 
<copyright><![CDATA[静怡家园]]></copyright>
<item>
<link>http://www.zhanghaijun.com/post//</link>
<title><![CDATA[shell实现秒级crontab计划任务]]></title> 
<author>碟舞飞扬 &lt;webmaster@zhanghaijun.com&gt;</author>
<category><![CDATA[Linux技术]]></category>
<pubDate>Wed, 15 Jun 2011 18:41:28 +0000</pubDate> 
<guid>http://www.zhanghaijun.com/post//</guid> 
<description>
<![CDATA[ 
	crontab是linux自带的计划任务程序，可以实现分，时，日，周，月。<br/><br/>但是crontab有两个缺陷：<br/>1.最小粒度为分，对于秒不支持<br/>2.若是上一个任务的执行时间超过下一个任务的开始时间的话，就会出现两个任务并行的现象，这样任务会越积越多，最后系统挂了。<br/>这周在项目里需要实现每隔10秒去执行任务的功能，因此写了个shell程序：<br/>1.可以自定义程序执行时间间隔，<br/>2.使用的是deamon方式，产生两个进程，父进程监控子进程，若是子进程挂了，父进程重新启动子进程，子进程负责每隔10秒钟执行任务；<br/>3.而且当任务执行时间超长时，不会出现两个任务同时执行的现象，下一个任务只会延后。也可以用后台运行方式运行任务，这样和crontab的效果一样<br/>4.若是时间间隔为10秒，而任务只执行了1秒，则sleep 9秒后，执行下一次任务<br/>5.若是把sleep改为usleep的话可以精确到微秒<br/><div class="quote"><div class="quote-title">引用</div><div class="quote-content">#运行执行 sh /Application/sdns/trigger/task_crontab.sh >> /Application/sdns/log/crontab.log 2>&1 <br/>#要定时执行的脚本，注意：不使用后台运行，则若是超过10秒的话，下一次会延迟，若是使用后台执行的话，有可能出现两个任务并行的问题 <br/>dlc_cmdline="sh /Application/sdns/trigger/dotask.sh >> /Application/sdns/log/dotask.log"; <br/>#本shell脚本的执行路径 <br/>dlc_thiscmd="sh /Application/sdns/trigger/task_crontab.sh >> /Application/sdns/log/crontab.log 2>&1" <br/>#任务执行时间间隔 <br/>dlc_task_timeout=10; <br/>#是否后台执行deamon <br/>is_deamon=$1; <br/>#deamon，父进程 <br/>if [ "$is_deamon" == "--deamon" ] <br/>then <br/>echo "deamon start" <br/>while [ 1 ] <br/>do <br/>date +"%F %T $dlc_thiscmd is started"; <br/>#调用子进程 <br/>$dlc_thiscmd <br/>date +"%F %T $dlc_thiscmd is ended"; <br/>done <br/>fi <br/>#子进程的代码 <br/>while [ 1 ] <br/>do <br/>date +"%F %T $dlc_cmdline is started" ; <br/>#记录本次程序开始时间 <br/>dlc_start_time=`date +%s` <br/>#执行任务 <br/>$dlc_cmdline <br/>#计算和时间间隔的差距 <br/>dlc_sleep_time=$(($dlc_task_timeout+$dlc_start_time-`date +%s`)); <br/>echo "sleep_time=[$dlc_sleep_time]"; <br/>#不够10秒，则sleep到10秒 <br/>if [ "$dlc_sleep_time" -gt 0 ] <br/>then <br/>sleep $dlc_sleep_time; <br/>fi <br/>date +"%F %T $dlc_cmdline is ended"; <br/>done <br/>转自：http://blog.chinaunix.net/space.php?uid=11121450&do=blog&id=274490</div></div><br/>Tags - <a href="http://www.zhanghaijun.com/tags/linux/" rel="tag">linux</a> , <a href="http://www.zhanghaijun.com/tags/crontab/" rel="tag">crontab</a>
]]>
</description>
</item><item>
<link>http://www.zhanghaijun.com/post//#blogcomment</link>
<title><![CDATA[[评论] shell实现秒级crontab计划任务]]></title> 
<author> &lt;user@domain.com&gt;</author>
<category><![CDATA[评论]]></category>
<pubDate>Thu, 01 Jan 1970 00:00:00 +0000</pubDate> 
<guid>http://www.zhanghaijun.com/post//#blogcomment</guid> 
<description>
<![CDATA[ 
	
]]>
</description>
</item>
</channel>
</rss>