解决Crontab定时任务重复运行的问题
在服务器端编写脚本并配置到crontab进行定时执行时,随着时间推移,常会遇到旧任务尚未结束、新任务又已启动的情况,从而导致系统资源被大量占用。针对这一重复运行问题,以下提供两种解决方案。
第一种方案是利用Linux系统的正则匹配机制。具体实现如下: 复制代码 代码如下: function ifrun($clsname,$bf = 0) { //下面进行检测,如有一个进程正在运行,则不运行 $str=shell_exec("/bin/ps ax > /home/root/".$clsname."_run.txt"); $str=shell_exec("/bin/grep -c '".$clsname.".php' /home/root/".$clsname."_run.txt"); if($bf >0) { if($str >=$bf) { return 1; } else { return 0; } } else { if ($str>=2) { return 1; } else { return 0; } } }
该函数的调用方式如下:
复制代码 代码如下: if (ifrun('pooy',5)) { die("pooy is running"); }
备注:pooy是程序pooy.php的名称!
第二种:把进程写到文件里面,然后用file函数去读取然后去匹配字符串 复制代码 代码如下: system('ps -ef |grep wget > /root/pooy.txt'); $arr=file('/root/pooy.txt'); $total=count($arr); for($i=0;$i<$total;$i++){ $count=array(); if(stristr($arr[$i],'www/pooy') !== FALSE) { //echo '"earth" not found in string'; $count[]='no'; break; } } if(count($count) >= 1 ) { echo "A same programs are running"; exit(); }else { echo "start__________________________________________________"; } 注:”www/pooy” 是程序里面包含的字符串!
通过上述方法,现在在Linux环境下运行PHP程序时,能否更顺畅地控制进程状态呢?