php - 我怎样才能使一个 php 脚本与 Cron Job 一起永远运行?

标签 php

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

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

最佳答案

不要忘记将最大执行时间设置为无限(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`

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

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

关于php - 我怎样才能使一个 php 脚本与 Cron Job 一起永远运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11132751/

相关文章:

php 代码未使用 wamp 服务器从 mysql 数据库获取数据

php - 我的网站在整个文件中注入(inject)了 javascript

javascript - 在php中从数据库中获取值并将其存储在js文件中的数组中

php - Facebook 点赞框 - 能够使用动态 URL 点赞当前页面

php - 使用 php/mysql/jQuery 随机聊天

php - 验证失败后重新加载页面时,保留 SQL 生成表单的原始顺序(随机)

javascript - Chart js PHP 和 JSON 不会显示

php - SQL从一个列复制数据到另一个表的指定列

php - 如何在 PHP 中按子午线(AM/PM)对时间排序

javascript - 我无法使用 ajax 在 wordpress 中将 $_POST 从 js 获取到 php