每次 php 从 sleep() 唤醒时,我都想重复检查一个变量。此外,如果 3 分钟后仍未找到特定变量,则该函数应停止检查。我该怎么办?这是我到目前为止的代码:
<?php
$file = file_get_contents("file.txt");
if($file == 0){
sleep(3);// then go back to $file
} else {
//stuff i want
}
?>
每次 php 从 sleep() 唤醒时,我都想重复检查一个变量。此外,如果 3 分钟后仍未找到特定变量,则该函数应停止检查。我该怎么办?这是我到目前为止的代码:
<?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
}
?>
<?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.
}