今天整理一點PHP原生實現進程的方式,死循環。針對進程一般要借助於定時去檢查進程的重啟與銷毀,也可以依賴於文件,或者配置自我實現重啟。
而php一般的死循環實現方式如下:
1 function doAnalisis($param1,$param2){ 2 $runFile = ROOT_PATH."Log/runprocess/player{$param1}.{$param2}.run"; 3 $dieFile = ROOT_PATH."Log/runprocess/player{$param1}.{$param2}.die"; 4 clearstatcache(); // 清除文件緩存,不然獲取最后訪問時間會出錯 5 //判斷是否需要重啟 6 if(file_exists($runFile)){ 7 //重啟檢測設為300s,當300s中未對runFile進行訪問時,重啟進程 8 if(time() - fileatime($runFile) < 300){ 9 return; 10 }else{ 11 $pid = file_get_contents($runFile); 12 shell_exec("ps aux | grep '{$_SERVER['PHP_SELF']}' | grep 'Cms/Process/playAnalisis/roomid/{$param1}&pNum={$param2}' | grep -v 'grep' | awk '{print $2}' | grep {$pid} | xargs --no-run-if-empty kill"); 13 } 14 } 15 16 //啟動進程 17 if(!file_put_contents($runFile, getmypid())){ 18 return; 19 } 20 //處理牌局 21 while (true) { 22 //檢查重啟 23 if(file_exists($dieFile)){ 24 unlink($runFile) && unlink($dieFile); 25 return; 26 } 27 //更新文件修改時間 28 29 touch($runFile); 30 //從緩存或者從其它地方獲取數據來源 31 $data = []; 32 33 if( empty($data) ){ 34 sleep(1); 35 continue; 36 } 37 38 //業務邏輯處理 39 foreach($data as $gamb) { 40 41 } 42 } 43 }
說明:
通過while touch不斷的修改文件的修改時間來確保進程的運行態。
通過檢查run文件的修改時間來判斷進程是否不存在需要重啟 。
可以根據傳遞的參數啟動多個進程對數據進行處理。