Kahlan\Code\Code::spin PHP Method

spin() public static method

Executes a callable in a loop until a timeout is reached or the callable returns true.
public static spin ( Callable $callable, integer $timeout, $delay = 100000 ) : mixed
$callable Callable The callable to execute.
$timeout integer The timeout value.
return mixed
    public static function spin($callable, $timeout = 0, $delay = 100000)
    {
        if (!is_callable($callable)) {
            throw new InvalidArgumentException();
        }
        $closure = function () use($callable, $timeout, $delay) {
            $timeout = (double) $timeout;
            $result = false;
            $start = microtime(true);
            do {
                if ($result = $callable()) {
                    return $result;
                }
                usleep($delay);
                $current = microtime(true);
            } while ($current - $start < $timeout);
            throw new TimeoutException("Timeout reached, execution aborted after {$timeout} second(s).");
        };
        if (!function_exists('pcntl_signal')) {
            return $closure();
        }
        return static::run($closure, $timeout);
    }

Usage Example

Beispiel #1
0
 /**
  * Runs the expectation.
  *
  * @param Closure $closure The closure to run/spin.
  */
 protected function _spin($closure)
 {
     if (($timeout = $this->timeout()) < 0) {
         $closure();
     } else {
         Code::spin($closure, $timeout);
     }
 }
All Usage Examples Of Kahlan\Code\Code::spin