如何在 PHP 中递归调用具有特定时间延迟的函数



我必须每 5 秒递归调用一个函数 10 次。我尝试过睡眠功能,但它不起作用或我实现错误。

任何建议如何实现?

如果你做一个递归函数,让它休眠 n 秒,然后再调用自己怎么办?一旦你完成了这些东西,你就可以停止它。 创建一个变量并存储函数在 10 次不再调用该函数后执行的次数。

<?php
function do_stuff(){
// do something
sleep(2); // wait 2 seconds
//condition to check whatever you were repeating
if(!$condition)
do_stuff(); //call this function again
}
?>

我认为第一个问题是。你能在 10 秒内调用该函数 5 次吗?

您可以执行以下操作:

// return time in seconds
start_time = microtime(true);
while(true) {
//call function x 10
// 5 seconds minus the run time of calling the function 10x
pause_time = 5 - (microtime(true) -  start_time);
sleep(pause_time); 
}