2014-09-05 105 views
4

我是新來的PHP,感謝您的時間:)PHP永無止境的循環

我需要的功能,通過它excutes自己在PHP whitout corn.for的幫助,我有下面的代碼川方這對我很好,但因爲它是一個永無止境的循環,它會給我的服務器或腳本造成任何問題,如果是的話給我一些建議或替代方案。謝謝。

$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)); 
} 
+0

你想要一個php守護進程 – 2014-09-05 03:13:57

+0

就我個人而言,我不會使用PHP守護進程。可能會遇到內存泄漏,每個月都會重新啓動。我會建議使用不同的符合語言。 – 2014-09-05 03:17:09

+0

作爲你的新的PHP也許你應該解釋爲什麼你需要這個,有可能是一個更好的主意 – 2014-09-05 03:17:12

回答

4

我們已經在實時系統環境中使用了無限循環來基本上等待傳入的SMS並對其進行處理。我們發現這樣做會導致服務器資源隨着時間的推移而不斷增加,必須重新啓動服務器才能釋放內存。

我們遇到的另一個問題是,當您在瀏覽器中執行帶有無限循環的腳本時,即使您點擊停止按鈕,它仍會繼續運行,除非您重新啓動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命令可以被認爲是窮人將進程作爲守護程序運行的方式。

+0

從命令行調用php腳本不會使其成爲守護進程 – 2014-09-05 03:29:20

+0

這種過程是Apache和PHP不擅長的,但像node.js這樣的新技術可以做到 - IMO這些類型的任務不應該是用PHP完成,它不可避免地會回來並咬你。 – 2014-09-05 03:33:03

+0

@Dagon什麼使它成爲一個守護進程? – zoltar 2015-11-18 05:27:30

0

while(1)表示它是無限循環。如果你想打破它,你應該使用條件break。例如, 。

while (1){ //infinite loop 
    $now=time(); 
    #do the routine job, trigger a php function and what no. 
    sleep($interval*60-(time()-$now)); 
    if(condition) break; //it will break when condition is true 
} 
+0

actully我不希望它打破,我只是想知道後果是什麼。 – alagu 2014-09-05 03:10:19

1

您可以使用time_sleep_until()函數。這將返回true或false

$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. 
    } 
1

有很多種方法來創建一個PHP守護進程,並且已經很長一段時間。

只是在背景中運行的東西不好。例如,如果它試圖打印某些內容並關閉控制檯,程序就會死亡。我已經在Linux上使用

一種方法是在PHP-CLI腳本,基本上是將您的腳本到兩個PID pcntl_fork()。讓父進程自行終止,並讓子進程再次自行分叉。再次讓父進程自殺。孩子進程現在將完全離婚,並且可以隨心所欲地進行任何你想做的事情。

$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. 

不幸的是,如果此模型崩潰或服務器重新引導,則無法自行重新啓動。 (這可以通過創意來解決,但是...)

爲了獲得重生的穩健性,請嘗試使用Upstart腳本(如果您使用Ubuntu。)Here is a tutorial - 但我還沒有嘗試過這種方法。

+0

剛剛發現[運行PHP腳本作爲守護進程](https://stackoverflow.com/questions/2036654/run-php-script-as-daemon-process「腳本溢出問題」),它比全面回答這個問題我有。 – Amgine 2014-09-05 14:54:34