public function consume($tokens)
{
while (!$this->bucket->consume($tokens, $seconds)) {
// avoid an overflow before converting $seconds into microseconds.
if ($seconds > 1) {
// leave more than one second to avoid sleeping the minimum of one millisecond.
$sleepSeconds = (int) $seconds - 1;
sleep($sleepSeconds);
$seconds -= $sleepSeconds;
}
// sleep at least 1 millisecond.
usleep(max(1000, $seconds * 1000000));
}
}
/** * Tests consume() won't sleep less than one millisecond. * * @test */ public function testMinimumSleep() { $rate = new Rate(10, Rate::MILLISECOND); $bucket = new TokenBucket(1, $rate, new SingleProcessStorage()); $bucket->bootstrap(); $consumer = new BlockingConsumer($bucket); $time = microtime(true); $consumer->consume(1); $this->assertLessThan(1.0E-5, abs(microtime(true) - $time - 0.001)); }