Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
722 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...