作为程序员一定要保持良好的睡眠,才能好编程

Linux Crontab 定时任务跑批php遇到超时处理方式

发布时间:2020-05-14



c.php
<?php
#$sleep=rand(1,5);
#sleep($sleep);

$count=file_get_contents('/home/songyongzhan/count.txt');
$count=intval($count);
file_put_contents('/home/songyongzhan/a.txt',"\n{$count}=======start=======".date('Y-m-d H:i:s').'     '.sprintf("%.4f",microtime(true))."\n",FILE_APPEND);
$sleep=rand(90,90);
sleep($sleep);

#file_put_contents('/home/songyongzhan/a.txt',"\nsleep {$sleep}\n",FILE_APPEND);
file_put_contents('/home/songyongzhan/a.txt',date('Y-m-d H:i:s').'     '.sprintf("%.4f",microtime(true))."次数 {$count}\n",FILE_APPEND);
file_put_contents('/home/songyongzhan/a.txt',"\n=======end======={$count}\n",FILE_APPEND);

$count=$count+1;
file_put_contents('/home/songyongzhan/count.txt',$count);


runResult.php
<?php
$cmd='ps -ef | grep /home/songyongzhan/c.php | grep -v "grep"';

while(true){
$result=[];
exec($cmd,$result,$code);

//if($code==0){
 echo "cmd run ".$code.' '.date('Y-m-d H:i:s')."  ".microtime(true). " \n";
 print_r($result);
 echo "\n";
//}

 print_r($result);
usleep(100000);

当计划任务执行的时候,这里可以检测到脚本执行,结果如下

cmd run 0 2019-08-10 16:12:01  1565424721.702 
Array
(
    [0] => root      3550  3546  0 16:12 ?        00:00:00 /bin/sh -c /usr/local/php-7.2.2/bin/php /home/songyongzhan/c.php >> /home/songyongzhan/c_run.log
)

Array
(
    [0] => root      3550  3546  0 16:12 ?        00:00:00 /bin/sh -c /usr/local/php-7.2.2/bin/php /home/songyongzhan/c.php >> /home/songyongzhan/c_run.log
)




linux定时任务

crontab -e   

* * * * * /usr/local/php-7.2/php   /home/songyongzhan/c.php  >> rr.php


php


结果:


bbbb.jpg



结论:

crontab  跑脚本,遇到脚本在规定的时间内,没有执行完毕,又到了下一次脚本执行时间,这两次互不影响,

php会另外起一个进程去跑。



j记住:


执行的脚本确保是多线程安全的,否则,会出现数据重复消费、重复执行的问题。