这是我的伪代码
For loop repeat 30 times
Call and execute API script which takes less than 1 second
I want the system sleep for some moment(less than 1 second)
Loop end
我希望上面的脚本应该在最少30秒内完成执行(2-3秒不是问题,但一定不能少)。 你能为我写一个示例代码(只有时间相关)
先谢谢
答案 0 :(得分:1)
这是一个实现我相信你所寻找的本质的小程序:
$minTime = 30;
$perSec = 10000;
$start = microtime(TRUE)*$perSec;
print("This must take $minTime seconds.\n");
// Replace this loop with what you actually need done
for ($i=0; $i<10; $i++) { print("Doing stuff #{$i}... "); sleep(1); }
// Check difference in timestamps to calculate remaining time
$remain=($minTime*$perSec-(microtime(TRUE)*$perSec-$start))/$perSec;
var_dump(['remain' => $remain]);
if ($remain > 0) {
print("\n$remain seconds remaining... ");
sleep($remain);
}
print("DONE\n");
此代码已更新为使用microtime()
而非time()
,其仅允许整数秒的间隔。在支持gettimeofday()
的系统上,我们可以使用微秒,而不是。