PHP sleep()用于特定的代码块

时间:2014-04-03 03:34:26

标签: php for-loop sleep continue usleep

我需要将正在运行的循环的continue语句延迟一定的微秒数。但是,我希望循环的其余部分运行,然后我只是希望它在时间结束时停止运行并continue,即使循环中的某些内容未被撤消。我知道这段代码不起作用,但这正是我想象的:

for ($_x = 0; $_x < 10; $_x++){
    usleep (1000){
        continue;
    }

    // ... do other stuff here until timer is up

    // when the timer runs out, continue to the next iteration
}

提前致谢。

3 个答案:

答案 0 :(得分:0)

尝试PHP Threads

  

当调用Thread的start方法时,run方法代码将在异步的Thread中执行。

答案 1 :(得分:0)

听起来你想做点什么:

$time = time() + 1;
for($_x = 0; $_x < 10 && $time > time(); $_x++){}

OR

$time = time() + 1;
for($_x = 0; $_x < 10; $_x++){
    if($time > time()){
        continue;
    }
}
或许或许?将if($time > time(){continue;}添加到多个位置,例如

function too_long($time){
    if($time > time()){
        return TRUE;
    }else{
        return FALSE;
    }
}

for($_x = 0; $_x < 10; $_x++){
    $time = time() + 1;
    //block of code
    if(too_long($time)){
        continue;
    }
    //block of code
    if(too_long($time)){
        continue;
    }
    ...
}

答案 2 :(得分:0)

这就是你想要的。我已经转换为睡眠1而不是睡眠以证明它有效,但是如果你将它切换回来它就能完成你想要的。你很受欢迎。

function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

for ($_x = 1; $_x < 11; $_x++) {
    $_m = microtime_float();
    $_v = sleep(1);
    $_n = microtime_float();
    do{
        //script here
        echo "<hr></br>".$_m."</br>".$_n ."</br>" .$_x;
    }
    while($_v);
}

输出

1396497686.9354 1396497687.9356 1

1396497687.9357 1396497688.9363 2

1396497688.9364 1396497689.937 3

1396497689.9371 1396497690.9381 4

1396497690.9381 1396497691.9392 5

1396497691.9393 1396497692.9398 6

1396497692.9399 1396497693.9406 7

1396497693.9406 1396497694.9415 8

1396497694.9415 1396497695.9424 9

1396497695.9424 1396497696.9427 10