10
<?php
 while(true){
 //code goes here.....
 }
  ?>

我想制作一个 PHP Web 服务器,那么如何使用 Curl 让这个脚本永远运行呢?

4

4 回答 4

23

不要忘记将最大执行时间设置为无限(0)。

如果这是您的意图,最好确保您不运行多个实例:

ignore_user_abort(true);//if caller closes the connection (if initiating with cURL from another PHP, this allows you to end the calling PHP script without ending this one)
set_time_limit(0);

$hLock=fopen(__FILE__.".lock", "w+");
if(!flock($hLock, LOCK_EX | LOCK_NB))
    die("Already running. Exiting...");

while(true)
{

    //avoid CPU exhaustion, adjust as necessary
    usleep(2000);//0.002 seconds
}

flock($hLock, LOCK_UN);
fclose($hLock);
unlink(__FILE__.".lock");

如果在 CLI 模式下,只需运行该文件。

如果在网络服务器上的另一个 PHP 中,您可以启动一个必须像这样无限运行的 PHP(而不是使用 cURL,这消除了依赖性):

$cx=stream_context_create(
    array(
        "http"=>array(
            "timeout" => 1, //at least PHP 5.2.1
            "ignore_errors" => true
        )
    )
);
@file_get_contents("http://localhost/infinite_loop.php", false, $cx);

或者您可以使用 wget 从 linux cron 开始,如下所示:

`* * * * * wget -O - http://localhost/infinite_loop.php`

或者,您可以使用运行包含以下内容的 .bat 文件的 bitsadmin 从 Windows 调度程序开始:

bitsadmin /create infiniteloop
bitsadmin /addfile infiniteloop http://localhost/infinite_loop.php
bitsadmin /resume infiniteloop
于 2012-06-21T06:45:20.107 回答
3

For a php code to run forever, it should have the ff.:

  • set_time_limit(0); // so php won't terminate as normal, if you will be doing stuff that will take a very long processing time
  • handler for keeping the page active [usually by setting up a client-side script to call the same page in intervals] See setInterval(), setTimeout()

EDIT: But since you will be setting up a cron job then you can keep away from the client-side handling.

EDIT: My suggestion, is not to use infinite loops unless you have a code that tells it to exit the loop after some time. Remember, you will be calling the same page using a cron job, so there is no point in keeping the loop infinite. [edit] Otherwise, you will be needing a locking system as suggested by @Tiberiu-Ionuț Stan so only 1 instance may run each time the cron job is called.

于 2012-06-21T06:42:34.540 回答
1

默认情况下,否,因为 PHP 有执行时间限制。见:http ://www.php.net/manual/en/info.configuration.php#ini.max-execution-time

set_time_limit您可以通过设置值或在脚本中调用来使其永远运行(http://php.net/manual/en/function.set-time-limit.php)。

但我不推荐这样做,因为 PHP(由 HTTP 请求调用)并非设计为具有无限循环。如果可以,请改用本地脚本,或者定期请求页面以频繁执行任务。

如果您的网站经常被其他人浏览,您可以改为在每个页面中执行此操作。

(想象一下,如果有人多次请求脚本,您将运行多个实例)

于 2012-06-21T06:38:34.167 回答
0

You can make it happen only if you set set_time_limit(0) in your script, else it will stop execution after max_execution_time set in configuration.

And you are using while(true) condition, that will make your script to run always.

于 2012-06-21T06:41:44.440 回答