Runs all pending stream events.

If $timeout is 0, it will return immediately. If $timeout is null, it
will wait indefinitely.

@param float|null timeout
967610
protected function runStreams($timeout)
    {
        if ($this->readStreams || $this->writeStreams) {
            $read = $this->readStreams;
            $write = $this->writeStreams;
            $except = null;
            if (stream_select($read, $write, $except, (null === $timeout) ? null : 0, $timeout ? (int) ($timeout * 1000000) : 0)) {
                // See PHP Bug https://bugs.php.net/bug.php?id=62452
                // Fixed in PHP7
                foreach ($read as $readStream) {
                    $readCb = $this->readCallbacks[(int) $readStream];
                    $readCb();
                }
                foreach ($write as $writeStream) {
                    $writeCb = $this->writeCallbacks[(int) $writeStream];
                    $writeCb();
                }
            }
        } elseif ($this->running && ($this->nextTick || $this->timers)) {
            usleep(null !== $timeout ? intval($timeout * 1000000) : 200000);
        }
    }
300671
public function block($timeout, $callback = null)
    {
        $starting = time();

        while (! $this->acquire()) {
            if (time() - $timeout >= $starting) {
                throw new LimiterTimeoutException;
            }

            usleep(750 * 1000);
        }

        if (is_callable($callback)) {
            $callback();
        }

        return true;
    }
1366694
function run() {
  const current = now();
  const queue = timeoutQueue.slice();
  let interval = INTERVAL_MAX;

  timeoutQueue.length = 0;

  // Reset
  if (runRafId > 0 || runTimeoutId > 0) {
    stop();
  }

  for (let i = queue.length - 1; i >= 0; i--) {
    const item = queue[i];

    if (!item.cancelled) {
      const duration = item.time - current;

      if (duration <= 0) {
        if (isDev) {
          debug('timeout triggered for "%s" at %s', item.id, new Date().toLocaleTimeString());
        }
        item.fn.apply(item.fn, item.args);
      } else {
        // Store smallest duration
        if (duration < interval) {
          interval = duration;
        }
        timeoutQueue.push(item);
      }
    }
  }

  // Loop
  if (timeoutQueue.length > 0) {
    // Use raf if requested interval is less than cutoff
    if (interval < INTERVAL_CUTOFF) {
      runRafId = raf(run);
    } else {
      runTimeoutId = setTimeout(run, interval);
    }
  }
}
475762
public function iterate($timeout)
    {

        // call parent method and sleep for the default timeout
        parent::iterate($timeout);

        // collect the session garbage
        $this->collectGarbage();

        // profile the size of the sessions
        if ($profileLogger = $this->getProfileLogger()) {
            $profileLogger->info('Successfull collect garbage for the servlet engine\'s session manager');
        }
    }
224357
public function setRequestTimeout($timeout)
    {
        if (!is_int($timeout) || $timeout < 0) {
            throw new Exception("Invalid value supplied for request timeout: $timeout");
        }

        $this->requestTimeout = $timeout;
        return $this;
    }
922160
public function sleep($timeout)
    {
        $this->synchronized(function ($self) use ($timeout) {
            $self->wait($timeout);
        }, $this);
    }
67504
protected void checkTimeouts() {
		long now = System.currentTimeMillis();

		// Check timeouted promises
		PendingPromise pending;
		Iterator<PendingPromise> i = promises.values().iterator();
		boolean removed = false;
		while (i.hasNext()) {
			pending = i.next();
			if (pending.timeoutAt > 0 && now >= pending.timeoutAt) {

				// Action is unknown at this location
				pending.promise.complete(new RequestTimeoutError(this.nodeID, pending.action));
				i.remove();
				removed = true;
			}
		}

		// Check timeouted request streams
		IncomingStream stream;
		long timeoutAt;
		Iterator<IncomingStream> j = requestStreams.values().iterator();
		while (j.hasNext()) {
			stream = j.next();
			timeoutAt = stream.getTimeoutAt();
			if (timeoutAt > 0 && now >= timeoutAt) {
				stream.error(new RequestTimeoutError(this.nodeID, "unknown"));
				requestStreamWriteLock.lock();
				try {
					j.remove();
				} finally {
					requestStreamWriteLock.unlock();
				}
				removed = true;
			}
		}

		// Check timeouted response streams
		j = responseStreams.values().iterator();
		while (j.hasNext()) {
			stream = j.next();
			timeoutAt = stream.getTimeoutAt();
			if (timeoutAt > 0 && now >= timeoutAt) {
				stream.error(new RequestTimeoutError(nodeID, "unknown"));
				responseStreamWriteLock.lock();
				try {
					j.remove();
				} finally {
					responseStreamWriteLock.unlock();
				}
				removed = true;
			}
		}

		// Reschedule
		if (removed) {
			scheduler.execute(() -> {
				reschedule(Long.MAX_VALUE);
			});
		} else {
			prevTimeoutAt.set(0);
		}
	}
1051648
public static function run($callable, $timeout = 0)
    {
        if (!is_callable($callable)) {
            throw new InvalidArgumentException();
        }

        $timeout = (integer) $timeout;

        if (!function_exists('pcntl_signal')) {
            throw new Exception("PCNTL threading is not supported by your system.");
        }

        pcntl_signal(SIGALRM, function ($signal) use ($timeout) {
            throw new TimeoutException("Timeout reached, execution aborted after {$timeout} second(s).");
        }, true);

        pcntl_alarm($timeout);

        $result = null;

        try {
            $result = $callable();
            pcntl_alarm(0);
        } catch (Throwable $e) {
            pcntl_alarm(0);
            throw $e;
        } catch (Exception $e) {
            pcntl_alarm(0);
            throw $e;
        }

        return $result;
    }
1094715
public function receive($timeout = 0)
    {
        $startAt = microtime(true);

        while (true) {
            $message = $this->receiveMessage();

            if ($message) {
                return $message;
            }

            if ($timeout && (microtime(true) - $startAt) >= $timeout) {
                return;
            }

            usleep($this->pollingInterval);

            if ($timeout && (microtime(true) - $startAt) >= $timeout) {
                return;
            }
        }
    }
1327635
public function wait($timeout = 60)
    {
        $timeoutMicro = $timeout !== null ? microtime(true) + (float)$timeout : null;
        while ($this->isRunning()) {
            if ($timeout !== null && microtime(true) >= $timeoutMicro) {
                return null;
            }
            usleep(1000);
        }

        return $this->getExitCode();
    }
670587
protected function wait_channel($channel_id, $timeout = 0)
    {
        // Keeping the original timeout unchanged.
        $_timeout = $timeout;
        while (true) {
            $now = time();
            try {
                list($frame_type, $frame_channel, $payload) = $this->wait_frame($_timeout);
            } catch (AMQPTimeoutException $e) {
                if ( $this->heartbeat && microtime(true) - ($this->heartbeat*2) > $this->last_frame ) {
                    $this->debug->debug_msg("missed server heartbeat (at threshold * 2)");
                    $this->setIsConnected(false);
                    throw new AMQPHeartbeatMissedException("Missed server heartbeat");
                }

                throw $e;
            }

            $this->last_frame = microtime(true);

            if ($frame_channel === 0 && $frame_type === 8) {
                // skip heartbeat frames and reduce the timeout by the time passed
                $this->debug->debug_msg("received server heartbeat");
                if($_timeout > 0) {
                    $_timeout -= time() - $now;
                    if($_timeout <= 0) {
                        // If timeout has been reached, throw the exception without calling wait_frame
                        throw new AMQPTimeoutException("Timeout waiting on channel");
                    }
                }
                continue;

            } else {

                if ($frame_channel == $channel_id) {
                    return array($frame_type, $payload);
                }

                // Not the channel we were looking for.  Queue this frame
                //for later, when the other channel is looking for frames.
                // Make sure the channel still exists, it could have been
                // closed by a previous Exception.
                if (isset($this->channels[$frame_channel])) {
                    array_push($this->channels[$frame_channel]->frame_queue, array($frame_type, $payload));
                }

                // If we just queued up a method for channel 0 (the Connection
                // itself) it's probably a close method in reaction to some
                // error, so deal with it right away.
                if (($frame_type == 1) && ($frame_channel == 0)) {
                    $this->wait();
                }
            }
        }
    }
1273429
public void setTimeout(int timeout) {
    this.timeout = timeout;
    try {
      socket.setSoTimeout(timeout);
    } catch (SocketException sx) {
      LOGGER.warn("Could not set socket timeout.", sx);
    }
  }
985071
function until($func,$args=NULL,$timeout=60) {
		if (!$args)
			$args=[];
		$time=time();
		$max=ini_get('max_execution_time');
		$limit=max(0,($max?min($timeout,$max):$timeout)-1);
		$out='';
		// Turn output buffering on
		ob_start();
		// Not for the weak of heart
		while (
			// No error occurred
			!$this->hive['ERROR'] &&
			// Got time left?
			time()-$time+1<$limit &&
			// Still alive?
			!connection_aborted() &&
			// Restart session
			!headers_sent() &&
			(session_status()==PHP_SESSION_ACTIVE || session_start()) &&
			// CAUTION: Callback will kill host if it never becomes truthy!
			!$out=$this->call($func,$args)) {
			if (!$this->hive['CLI'])
				session_commit();
			// Hush down
			sleep(1);
		}
		ob_flush();
		flush();
		return $out;
	}
147491
public function setTimeout($timeout)
    {
        if ($timeout === null) {
            $this->timeout = null;
            $this->onConfigChanged();
            return;
        }

        $timeout = (int)$timeout;

        if ($timeout < 0) {
            throw new Exception\InvalidArgumentException('$timeout must be between positive (0+)');
        }

        $this->timeout = $timeout;
        $this->onConfigChanged();
    }
691336
public function wait($timeout = -1)
    {
        $forever = ($timeout < 0);

        while ($this->isAlive()) {
            $this->read();

            if (!$forever && (microtime(true) - $this->start > $timeout)) {
                $this->kill(SIGKILL);
                break;
            }

            usleep(5000);
        }

        $this->cleanup();
    }
1235155
def wait_running(self, timeout=None):
        

        flag = self._running.wait(timeout)

        if flag is False:
            raise TimeoutExpiredError("Timeout waiting for thread to start running")
762977
public static function stream(iterable $responses, float $timeout = null): \Generator
    {
        $runningResponses = [];

        foreach ($responses as $response) {
            self::schedule($response, $runningResponses);
        }

        $lastActivity = microtime(true);
        $isTimeout = false;

        while (true) {
            $hasActivity = false;
            $timeoutMax = 0;
            $timeoutMin = $timeout ?? INF;

            /** @var ClientState $multi */
            foreach ($runningResponses as $i => [$multi]) {
                $responses = &$runningResponses[$i][1];
                self::perform($multi, $responses);

                foreach ($responses as $j => $response) {
                    $timeoutMax = $timeout ?? max($timeoutMax, $response->timeout);
                    $timeoutMin = min($timeoutMin, $response->timeout, 1);
                    $chunk = false;

                    if (isset($multi->handlesActivity[$j])) {
                        // no-op
                    } elseif (!isset($multi->openHandles[$j])) {
                        unset($responses[$j]);
                        continue;
                    } elseif ($isTimeout) {
                        $multi->handlesActivity[$j] = [new ErrorChunk($response->offset)];
                    } else {
                        continue;
                    }

                    while ($multi->handlesActivity[$j] ?? false) {
                        $hasActivity = true;
                        $isTimeout = false;

                        if (\is_string($chunk = array_shift($multi->handlesActivity[$j]))) {
                            $response->offset += \strlen($chunk);
                            $chunk = new DataChunk($response->offset, $chunk);
                        } elseif (null === $chunk) {
                            $e = $multi->handlesActivity[$j][0];
                            unset($responses[$j], $multi->handlesActivity[$j]);
                            $response->close();

                            if (null !== $e) {
                                $response->info['error'] = $e->getMessage();

                                if ($e instanceof \Error) {
                                    throw $e;
                                }

                                $chunk = new ErrorChunk($response->offset, $e);
                            } else {
                                $chunk = new LastChunk($response->offset);
                            }
                        } elseif ($chunk instanceof ErrorChunk) {
                            unset($responses[$j]);
                            $isTimeout = true;
                        } elseif ($chunk instanceof FirstChunk && $response->logger) {
                            $info = $response->getInfo();
                            $response->logger->info(sprintf('Response: "%s %s"', $info['http_code'], $info['url']));
                        }

                        yield $response => $chunk;
                    }

                    unset($multi->handlesActivity[$j]);

                    if ($chunk instanceof FirstChunk && null === $response->initializer) {
                        // Ensure the HTTP status code is always checked
                        $response->getHeaders(true);
                    } elseif ($chunk instanceof ErrorChunk && !$chunk->didThrow()) {
                        // Ensure transport exceptions are always thrown
                        $chunk->getContent();
                    }
                }

                if (!$responses) {
                    unset($runningResponses[$i]);
                }

                // Prevent memory leaks
                $multi->handlesActivity = $multi->handlesActivity ?: [];
                $multi->openHandles = $multi->openHandles ?: [];
            }

            if (!$runningResponses) {
                break;
            }

            if ($hasActivity) {
                $lastActivity = microtime(true);
                continue;
            }

            switch (self::select($multi, $timeoutMin)) {
                case -1: usleep(min(500, 1E6 * $timeoutMin)); break;
                case 0: $isTimeout = microtime(true) - $lastActivity > $timeoutMax; break;
            }
        }
    }