Setting PHP timer based functions

2019-06-23 23:29发布

I have a php file test.php. I want to echo or print "Success" after 5 seconds, soon after the php file is called or loaded or opened by the browser. Btw, Sometimes I may want to execute / initialise some functions after a specific interval of time.

Can anybody tell / suggest me how can I make a time-oriented task using php, like printing a message after 5 seconds??

Thanks in advance..

标签: php timer
5条回答
来,给爷笑一个
2楼-- · 2019-06-23 23:53

You can interrupt the execution of your script using sleep(). If you want sub-second precision, you can use usleep():

# wait half a second (500ms)
usleep(500000);
echo 'Success';
查看更多
beautiful°
3楼-- · 2019-06-24 00:00
while(1){
    sleep($time);
    youfunction();
}
查看更多
smile是对你的礼貌
4楼-- · 2019-06-24 00:06

If you have to, you can use this: http://php.net/manual/en/function.register-tick-function.php but watch out for impact on performance.

In the called function you check if enough time has passed, and if so unregister the tick function and then run the appropriate code.

查看更多
【Aperson】
5楼-- · 2019-06-24 00:07

It is usually not a good idea to do this in PHP. The PHP script should run as quickly as possible. Delaying the PHP execution of the PHP script

  • is going to use more server resources than necessary
  • could meet timeout limits in PHP, on the server or in the browser.

The best alternative is JavaScript and its setTimeout():

setTimeout(function() { alert ("Done!"); }, 5000); 

(alternatively, instead of alert(), you could instruct JavaScript to show a dialog or similar.)

if you do not want to depend on JavaScript, you could consider a META redirect taking the user to a page containing the "Done!" message.

<meta http-equiv="refresh" content="5; url=http://example.com/">
查看更多
不美不萌又怎样
6楼-- · 2019-06-24 00:15

You can use jQuery timer to delay execution of subsequent items in the queue

http://api.jquery.com/delay/

http://www.w3schools.com/js/js_timing.asp

<html>
<head>
<script type="text/javascript">
function timeMsg()
{
var t=setTimeout("alertMsg()",3000);
}
function alertMsg()
{
alert("Hello");
}
</script>
</head>

<body>
<form>
<input type="button" value="Display alert box in 3 seconds"
onclick="timeMsg()" />
</form>
</body>
</html>
查看更多
登录 后发表回答