我想每次從睡眠()喚醒時重複檢查一個變量。此外,如果3分鐘沒有找到特定的變量,那麼該函數應該停止檢查。我將如何去做這件事?這是我到目前爲止的代碼:PHP在喚醒後重復進度
<?php
$file = file_get_contents("file.txt");
if($file == 0){
sleep(3);// then go back to $file
} else {
//stuff i want
}
?>
我想每次從睡眠()喚醒時重複檢查一個變量。此外,如果3分鐘沒有找到特定的變量,那麼該函數應該停止檢查。我將如何去做這件事?這是我到目前爲止的代碼:PHP在喚醒後重復進度
<?php
$file = file_get_contents("file.txt");
if($file == 0){
sleep(3);// then go back to $file
} else {
//stuff i want
}
?>
如果你想繼續做某件事,直到發生其他事情,你需要一個循環。你有兩件事要檢查你是否應該退出循環:文件變量和時間長度。您需要添加一個變量來跟蹤時間,或者您需要檢查每次循環的時間並將其與開始時間進行比較。
<?php
$file = file_get_contents("file.txt");
$timesChecked = 0;
while($file == 0 and $timesChecked < 60)
{
sleep(3);
$timesChecked++;
$file = file_get_contents("file.txt");
}
if($file != 0)
{
// stuff i want
} else {
// 3 minutes elapsed
}
?>
請注意,這個函數至少會運行6000秒或100分鐘,請注意,根據操作系統如何決定處理進程,睡眠可能不會在三秒內完成。因此,即使$ timesChecked設置爲<60,仍然可以運行三分鐘以上,但數量不確定。 –
@NathanielFord:謝謝。我認爲睡眠()需要幾微秒或什麼,然後我做錯了數學。 :)你對這種方法的不精確性絕對正確。如果3分鐘是精確度要求,最好與'時間()'進行比較。 http://us.php.net/time –
如何使頁面正常加載而無需等待$文件成爲別的東西 –
<?php
//This function returns false if the time elapses without finding the variable.
//Otherwise it executes what you want to do. It could instead return true if that makes sense.
function waitForContent($filename) {
$timeElapsed = 0;
$lastTry = 0;//the time the file was last checked for contents
$filehandler = file_get_contents($filename);
while ($filehandler == 0) {
$currentTime = microtime();//current time in microseconds
$timeElapsed = $currentTime - $lastTry;//Note this may not be three seconds, due to how sleep works.
$lastTry = currentTime;//update the time of the last trye
if ($timeElapsed > (180 * 1000)) {//if three minutes has passed, quit.
return false;
}
sleep(3);
$filehandler = file_get_contents($filename);//update file handler
}
stuffIWantToDo();//stuff you want to do function.
}
發佈您的代碼..你有多遠試過.. – Broncha
...並請解釋更好你試圖做 –
編輯什麼... :(@票 –