加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

如何让PHP脚本永远与Cron Job一起运行?

发布时间:2020-12-13 13:49:56 所属栏目:PHP教程 来源:网络整理
导读:?php while(true){ //code goes here..... } ? 我想制作一个PHP Web服务器,那么如何使用Curl使这个脚本永远运行? 不要忘记将最大执行时间设置为无限(0). 如果这是你的意图,那么最好确保你不要运行多个实例: ignore_user_abort(true);//if caller closes th
<?php
 while(true){
 //code goes here.....
 }
  ?>

我想制作一个PHP Web服务器,那么如何使用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模式下,只需运行该文件.

如果在Web服务器上的另一个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运行.bat文件从Windows Scheduler启动,该文件包含以下内容:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读