php time 循环不变,PHP为系统调用的脚本设置超时,set_time_limit不起作用
我有一個命令行PHP腳本,使用foreach使用數組的每個成員運行wget請求.這個wget請求有時可能需要很長時間,因此我希望能夠設置超時以殺死腳本(例如,如果超過15秒).我已禁用PHP安全模式并在腳本的早期嘗試了set_time_limit(15),但它會無限期地繼續.更新:感謝Dor指出這是因為set_time_limit()不尊重system()調用.
所以我試圖在執行15秒后找到其他方法來殺死腳本.但是,我不確定是否可以檢查腳本在同時處于wget請求中間時運行的時間(while循環不起作用).也許用一個定時器分叉一個進程并設置它在一段時間后殺死父進程?
謝謝你的任何提示!
更新:
以下是我的相關代碼. $url是從命令行傳遞的,是一個包含多個URL的數組(對不起,最初不發布):
foreach( $url as $key => $value){
$wget = "wget -r -H -nd -l 999 $value";
system($wget);
}
解決方法:
您可以使用“–timeout”和time()的組合.首先確定總共有多少時間,然后在腳本運行時降低–timeout.
例如:
$endtime = time()+15;
foreach( $url as $key => $value){
$timeleft = $endtime - time();
if($timeleft > 0) {
$wget = "wget -t 1 --timeout $timeleft $otherwgetflags $value";
print "running $wget
";
system($wget);
} else {
print("timed out!");
exit(0);
}
}
注意:如果你不使用-t,wget將嘗試20次,每次等待 – 超時秒.
這是使用proc_open / proc_terminate的一些示例代碼(@Josh的建議):
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("pipe", "w")
);
$pipes = array();
$endtime = time()+15;
foreach( $url as $key => $value){
$wget = "wget $otherwgetflags $value";
print "running $wget\n";
$process = proc_open($wget, $descriptorspec, $pipes);
if (is_resource($process)) {
do {
$timeleft = $endtime - time();
$read = array($pipes[1]);
stream_select($read, $write = NULL, $exeptions = NULL, $timeleft, NULL);
if(!empty($read)) {
$stdout = fread($pipes[1], 8192);
print("wget said--$stdout--\n");
}
} while(!feof($pipes[1]) && $timeleft > 0);
if($timeleft <= 0) {
print("timed out\n");
proc_terminate($process);
exit(0);
}
} else {
print("proc_open failed\n");
}
}
標簽:php,linux,command-line,windows
來源: https://codeday.me/bug/20190714/1457076.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的php time 循环不变,PHP为系统调用的脚本设置超时,set_time_limit不起作用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在linux下配置java,在Linux
- 下一篇: 快手颜值pk在哪里打开(快手短视频App