如何使 php 脚本永久运行与 Cron 作业


How can I make a php script to run forever with Cron Job?

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

我想做一个PHP的Web服务器,那么我怎样才能用Curl让这个脚本永远运行呢?

不要忘记将最大执行时间设置为 infin(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 模式下,只需运行该文件。

如果在Web服务器上的另一个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`

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

bitsadmin /create infiniteloop
bitsadmin /addfile infiniteloop http://localhost/infinite_loop.php
bitsadmin /resume infiniteloop

要使 php 代码永久运行,它应该具有 ff.:

  • set_time_limit(0);//所以 php 不会像正常一样终止,如果你要做的事情需要很长的处理时间
  • 用于保持页面活动的处理程序 [通常通过设置客户端脚本以间隔调用同一页面] 请参阅setInterval()setTimeout()

编辑:但是由于您将设置一个 cron 作业,因此您可以远离客户端处理。

编辑:我的建议是,不要使用无限循环,除非你有代码告诉它在一段时间后退出循环。请记住,您将使用 cron 作业调用同一页面,因此保持循环无限是没有意义的。[编辑]否则,您将需要 @Tiberiu-Ionuț Stan 建议的锁定系统,因此每次调用 cron 作业时只能运行 1 个实例。

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

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

但我不建议这样做,因为PHP(由HTTP请求调用)不是为了有一个无限循环而设计的。如果可以,请改用本地脚本,或者每隔一段时间请求页面以频繁执行任务。

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

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

只有在脚本中设置set_time_limit(0)时才能实现它,否则它将在配置中设置max_execution_time后停止执行。

并且您正在使用 while(true) 条件,这将使您的脚本始终运行。