Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP While循环在两小时后停止_Php - Fatal编程技术网

PHP While循环在两小时后停止

PHP While循环在两小时后停止,php,Php,我有以下脚本,每60秒循环一次。一切正常,但两三个小时后脚本就停止了。我不知道为什么 <?php // The worker will execute every X seconds: $seconds = 60; // We work out the micro seconds ready to be used by the 'usleep' function. $micro = $seconds * 1000000; while(true){ try {

我有以下脚本,每60秒循环一次。一切正常,但两三个小时后脚本就停止了。我不知道为什么

<?php

// The worker will execute every X seconds:
$seconds = 60;

// We work out the micro seconds ready to be used by the 'usleep' function.
$micro = $seconds * 1000000;

while(true){

    try {
        $url = 'URL';
        $fields = array(
            "hi"=> 1,
            "world"=> 2,
        );
        //url-ify the data for the POST
        foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
        $fields_string = rtrim($fields_string,'&');

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_POST,count($fields));
        curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
        curl_exec($ch);

    } catch (Exception $e) {
        $myFile = "/usr/share/test/filephp.txt";
        $fh = fopen($myFile, 'a') or die("Can't open file");
        $stringData = "File updated at: " . time(). "\n";
        fwrite($fh, $stringData);
        fclose($fh);
    }




    // Now before we 'cycle' again, we'll sleep for a bit...
    usleep($micro);
}

有什么想法吗?

您可以将其包装在bash脚本中,然后完全删除while循环

脚本“包装器”:

那就称之为脚本:

sudo -u root wrapper &

您在哪里运行上述代码?PHP将在预定时间后停止执行,除非您将其作为守护进程运行,可能是因为
max\u execution\u time
设置。但是为什么不把它作为cron作业而不是连续循环来运行呢?把它作为root来运行有点代码味道。这应该是没有必要的。这不是“一点代码味道”,而是一个巨大的禁忌!它尽可能地稳定。您可能需要使用“nohup”来防止在用户会话结束时挂断。它正在工作。谢谢我在“完成”之后加了“&”
#!/bin/bash

SECONDS=60
while [ 1 ]; do
    php -f /usr/share/test/test.php
    sleep $SECONDS
done
sudo -u root wrapper &