PHP唤醒后重复进度

时间:2012-06-15 17:50:47

标签: php

每次php从sleep()唤醒时我想反复检查一个变量。此外,如果在没有找到特定变量的情况下经过了3分钟,则该功能应该停止检查。我该怎么做?这是我到目前为止的代码:

<?php
  $file = file_get_contents("file.txt");
  if($file == 0){
    sleep(3);// then go back to $file
  } else {
    //stuff i want
  }
?>

2 个答案:

答案 0 :(得分:2)

如果你想继续做某事直到其他事情发生,你需要一个循环。你需要检查两件事,看看你是否应该退出循环:文件变量和时间长度。您需要添加一个变量来跟踪时间,或者需要在每次循环时检查时间并将其与开始时间进行比较。

<?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
     }
 ?>

答案 1 :(得分:1)

<?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.
  }