php永无止境的循环 [英] php never ending loop

查看:54
本文介绍了php永无止境的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个无需使用crone即可在php中自行执行的函数.我想出了下面的代码,对我来说很好用,但由于它是一个永无止境的循环,它将对我的服务器或脚本造成任何问题,如果可以,请给我一些建议或替代方法.谢谢.

I need a function that executes by itself in php without the help of crone. I have come up with the following code that works for me well but as it is a never-ending loop will it cause any problem to my server or script, if so could you give me some suggestion or alternatives, please. Thanks.

$interval=60; //minutes
set_time_limit(0);

while (1){
    $now=time();
    #do the routine job, trigger a php function and what not.
    sleep($interval*60-(time()-$now));
}

推荐答案

我们在实时系统环境中使用了无限循环来基本上等待传入的SMS并对其进行处理.我们发现以这种方式进行操作会使服务器资源随着时间的推移而变得密集,因此必须重新启动服务器以释放内存.

We have used the infinite loop in a live system environment to basically wait for incoming SMS and then process it. We found out that doing it this way makes the server resource intensive over time and had to restart the server in order to free up memory.

我们遇到的另一个问题是,当您在浏览器中执行具有无限循环的脚本时,即使您按了停止按钮,除非重新启动Apache,否则脚本将继续运行.

Another issue we encountered is when you execute a script with an infinite loop in your browser, even if you hit the stop button it will continue to run unless you restart Apache.

    while (1){ //infinite loop
    // write code to insert text to a file
    // The file size will still continue to grow 
    //even when you click 'stop' in your browser.
    }

解决方案是在命令行上以守护程序身份运行PHP脚本.方法如下:

The solution is to run the PHP script as a deamon on the command line. Here's how:

nohup php myscript.php&

& 将您的进程置于后台.

the & puts your process in the background.

我们不仅发现此方法占用的内存更少,而且还可以通过运行以下命令来终止它而无需重新启动apache:

Not only we found this method to be less memory intensive but you can also kill it without restarting apache by running the following command :

杀死进程ID

正如Dagon指出的那样,这实际上不是将PHP作为守护程序"运行的真正方法,但使用 nohup 命令可以被认为是可怜的人运行进程的方式,如下所示:守护程序.

As Dagon pointed out, this is not really the true way of running PHP as a 'Daemon' but using the nohup command can be considered as the poor man's way of running a process as a daemon.

这篇关于php永无止境的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆