bandwidthThrottle\tokenBucket\BlockingConsumer::consume PHP Method

consume() public method

If the underlying token bucket doesn't have sufficient tokens, the consumer blocks until it can consume the tokens.
public consume ( integer $tokens )
$tokens integer The token amount.
    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));
        }
    }

Usage Example

 /**
  * 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));
 }
BlockingConsumer