malkusch\lock\util\Loop::execute PHP Метод

execute() публичный Метод

The code has to be designed in a way that it can be repeated without any side effects. When execution was successful it should notify that event by calling {@link Loop::end()}. I.e. the only side effects of the code may happen after a successful execution. If the code throws an exception it will stop repeating the execution.
public execute ( callable $code ) : mixed
$code callable The executed code block.
Результат mixed The return value of the executed block.
    public function execute(callable $code)
    {
        $this->looping = true;
        $minWait = 100;
        $timeout = microtime(true) + $this->timeout;
        for ($i = 0; $this->looping && microtime(true) < $timeout; $i++) {
            $result = call_user_func($code);
            if (!$this->looping) {
                break;
            }
            $min = $minWait * pow(2, $i);
            $max = $min * 2;
            $usleep = rand($min, $max);
            usleep($usleep);
        }
        if (microtime(true) >= $timeout) {
            throw new TimeoutException("Timeout of {$this->timeout} seconds exceeded.");
        }
        return $result;
    }

Usage Example

Пример #1
0
 /**
  * Tests that the code is executed more times.
  *
  * @test
  */
 public function testIteration()
 {
     $i = 0;
     $loop = new Loop();
     $loop->execute(function () use($loop, &$i) {
         $i++;
         if ($i > 1) {
             $loop->end();
         }
     });
     $this->assertEquals(2, $i);
 }