我需要一个在php中自己执行的函数,而无需crone的帮助。我已经提出了下面的代码,对我来说很好,但由于它是一个永无止境的循环,它会不会给我的服务器或脚本带来任何问题,如果是这样,请给我一些建议或替代。谢谢。
$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));
}发布于 2014-09-05 03:27:51
我们已经使用无限循环在一个活动的系统环境中,基本上等待收到的短信,然后处理它。我们发现,这样做会使服务器资源随着时间的推移而变得密集,并不得不重新启动服务器以释放内存。
我们遇到的另一个问题是,当您在浏览器中执行一个具有无限循环的脚本时,即使您按下停止按钮,它也将继续运行,除非您重新启动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.
}解决方案是在命令行上作为deamon运行PHP脚本。下面是操作步骤:
nohup php myscript.php &
&将您的进程置于后台。
不仅我们发现这个方法占用的内存更少,而且您还可以通过运行以下命令来在不重新启动apache的情况下杀死它:
kill processid
编辑:正如达根所指出的,这并不是将PHP作为‘守护进程’运行的真正方式,但是使用nohup命令可以被看作是穷人将进程作为守护进程运行的方式。
发布于 2014-09-05 03:39:35
您可以使用直到()函数。它将返回真假。
$interval=60; //minutes
set_time_limit( 0 );
$sleep = $interval*60-(time());
while ( 1 ){
if(time() != $sleep) {
// the looping will pause on the specific time it was set to sleep
// it will loop again once it finish sleeping.
time_sleep_until($sleep);
}
#do the routine job, trigger a php function and what not.
}发布于 2014-09-05 04:22:26
有许多方法可以在php中创建守护进程,并且已经使用了很长一段时间。
只是在后台运行一些东西就不好了。例如,如果它试图打印什么,并且控制台关闭,程序就会死掉。
我在linux上使用的一种方法是php脚本中的叉(),它基本上将脚本分成两个PID。让父进程关闭自身,并让子进程分叉自身。同样,父进程也会自动关闭。孩子的过程现在将完全离婚,可以愉快地在后台闲逛,做任何你想做的事情。
$i = 0;
do{
$pid = pcntl_fork();
if( $pid == -1 ){
die( "Could not fork, exiting.\n" );
}else if ( $pid != 0 ){
// We are the parent
die( "Level $i forking worked, exiting.\n" );
}else{
// We are the child.
++$i;
}
}while( $i < 2 );
// This is the daemon child, do your thing here.不幸的是,如果该模型崩溃或服务器被重新启动,则无法重新启动它自己。(这可以通过创造力来解决,但是.)
要获得喘息的健壮性,可以尝试一个新贵脚本(如果您在Ubuntu.) 这里有一个教程 --但是我还没有尝试过这个方法。
https://stackoverflow.com/questions/25678062
复制相似问题