gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 22:19:27 25 4
gpt4 key购买 nike

<?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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com