打破后台运行的PHP脚本的无限循环[不会扼杀进程]


Breaking infinite loop of a PHP script running in background [not killing the process]

我有一个PHP脚本,它将在带有无限循环的VPS上全天候运行,但问题是,我如何在需要时打破PHP脚本中的无限循环,以使脚本正确存在?

我知道我可以终止进程,但如果我终止,脚本将立即停止我的循环大小非常大,如果在杀死进程时执行的是循环中间的某个地方,那么循环的其余一半将不会执行,这将产生错误。另外,我在循环之后有一些代码,所以若进程被终止,那个么代码就不会被执行。

所以我的问题是,如何在不扼杀进程的情况下,在需要时打破后台运行的PHP脚本的无限循环?

代替:

while(true) {

Do:

while(!file_exists("KILL")) {

然后,当您想要终止脚本时,只需创建kill文件。你可以通过一个kill.php脚本来为自己创建该文件,这样你就不必确切地记得该做什么了。

就我个人而言,我发现PHP脚本比控制台应用程序的EXE更容易使用,但这只是我的看法。

Q1。Windows任务计划程序。。不要插入任何循环,只需插入CGI目录,然后创建时间。

Q2.如果你问我,PHP会更好。

不过,这与性能无关。

听起来像是在为服务器编码,看看这个,希望它能有所帮助。

<?php
class ServerManager
{
    private $serverState;
    public function process()
    {
        if(!$this->getServerState())
        {
            return;
        }
        $this->processNewConnections();
        $this->processExistingConnections();
    }
    public function setServerState($state)
    {
        $this->serverState = $state;
    }
    public function getServerState()
    {
        return $this->serverState;
    }
    private function processNewConnections()
    {
        ...
    }
    private function processExistingConnections()
    {
        ...
        if(connected client has requested that the server should stop)
        {
            $this->setServerState(false);
        }
        ...
    }
}