php 如何在无限循环中每 4 分钟回显一次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12877692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:24:52  来源:igfitidea点击:

How to echo something every 4 minutes while in an endless loop

php

提问by Matt Jenkins

I have a script that uses while(true)to run so it runs forever until it dies. I want to be able to make it echo something once every 4 minutes, how can i do this? The script runs on command prompt and it uses while(true)so its confusing plus i am not sure how to make it do that every 4 minutes. How can i make it echo something once every 4 minutes while still in a while(true)?

我有一个while(true)用于运行的脚本,因此它会一直运行直到它死掉。我希望能够每 4 分钟回声一次,我该怎么做?该脚本在命令提示符下运行并使用它,while(true)因此它令人困惑,而且我不知道如何让它每 4 分钟执行一次。我怎样才能让它每 4 分钟回声一次,而仍然在 a 中while(true)

回答by Baba

You can try

你可以试试

while(true)
{
    sleep(240); // sleep for 240 sec
    echo " Hello World" ;
}

Or

或者

$time = time();
while ( true ) {
    /*
     * Play Some Ball
     */

    if ((time() - $time) >= 240) {
        echo date("Y:m:d g:i:s"), PHP_EOL;
        $time = time();
    }
    sleep(2);
}

Output Test with Time = 2 sec, Sleep = 1 sec

输出测试 Time = 2 sec, Sleep = 1 sec

2012:10:14 12:50:56
2012:10:14 12:50:58
2012:10:14 12:51:00
2012:10:14 12:51:02
2012:10:14 12:51:04
2012:10:14 12:51:06
2012:10:14 12:51:08
2012:10:14 12:51:10
2012:10:14 12:51:12
2012:10:14 12:51:14

回答by Lix

Using a sleepmethod will actually halt your script from running. I'm not 100% if this is what you want to happen.

使用sleep方法实际上会停止您的脚本运行。如果这是你想要发生的,我不是 100%。

Another way to attack this issue would be to compare timestamps from the last "echo" command on each iteration.

解决此问题的另一种方法是在每次迭代时比较最后一个“echo”命令的时间戳。

$echo_time = time();
$interval = 4*60;
while(true){
  if ($echo_time + $interval >= time()){
    echo "$interval seconds have passed...";
    $echo_time = time(); // set up timestamp for next interval
  }
  // other uninterrupted code goes here.
}

This will allow your code within your loop to continue running and only check the times at the start of each iteration.

这将允许循环中的代码继续运行,并且只在每次迭代开始时检查时间。

回答by Marin Sagovac

Try adding in a loop of while(true) { ... }sleep() parameter function.

尝试添加while(true) { ... }sleep() 参数函数的循环。

$sleep = 4*60;
while(true)
{
    # waiting...        
    sleep($sleep);
    # work after 240 mins
}