Handle one request at a time until shutdown.

        Polls for shutdown every poll_interval seconds. Ignores
        self.timeout. If you need to do periodic tasks, do them in
        another thread.
161911
def serve_forever(self, poll_interval=0.5):
        
        self._serving_event.set()
        self._shutdown_request_event.clear()
        TCPServer.serve_forever(self, poll_interval=poll_interval)
518095
def wait(self, seconds, poll_interval):
        
        # jid is None when all hosts were skipped
        if self.jid is None:
            return self.results

        clock = seconds - poll_interval
        while (clock >= 0 and not self.completed):
            time.sleep(poll_interval)

            poll_results = self.poll()

            for (host, res) in poll_results['polled'].iteritems():
                if res.get('started'):
                    self.runner.callbacks.on_async_poll(host, res, self.jid, clock)

            clock = clock - poll_interval

        return self.results
1117746
def stop_polling(self):
        
        if hasattr(self, '_polling') and self._polling:
            log.info('Stop polling...')
            self._polling = False
341092
def _poll(self):
        
        while True:
            self.poll_count += 1
            self._poll_action()
            if self.poll_complete:
                break
            time.sleep(self.poll_interval_s)
            self._poll_update_interval()
569215
def _poll(self) -> None:
        
        if self._subprocess is None:
            raise SublemonLifetimeError(
                'Attempted to poll a non-active subprocess')
        elif self._subprocess.returncode is not None:
            self._exit_code = self._subprocess.returncode
            self._done_running_evt.set()
            self._server._running_set.remove(self)
            self._server._sem.release()
534191
public void shutdownAndWait() {
		try {
			client.shutdown().get();
			LOG.info("The Queryable State Client was shutdown successfully.");
		} catch (Exception e) {
			LOG.warn("The Queryable State Client shutdown failed: ", e);
		}
	}
956263
def _do_poll_problems(self):
        
        try:
            # grouped futures (all scheduled within _POLL_GROUP_TIMEFRAME)
            frame_futures = {}

            def task_done():
                self._poll_queue.task_done()

            def add(future):
                # add future to query frame_futures
                # returns: worker lives on?

                # `None` task signifies thread termination
                if future is None:
                    task_done()
                    return False

                if future.id not in frame_futures and not future.done():
                    frame_futures[future.id] = future
                else:
                    task_done()

                return True

            while True:
                frame_futures.clear()

                # blocking add first scheduled
                frame_earliest, future = self._poll_queue.get()
                if not add(future):
                    return

                # try grouping if scheduled within grouping timeframe
                while len(frame_futures) < self._STATUS_QUERY_SIZE:
                    try:
                        task = self._poll_queue.get_nowait()
                    except queue.Empty:
                        break

                    at, future = task
                    if at - frame_earliest <= self._POLL_GROUP_TIMEFRAME:
                        if not add(future):
                            return
                    else:
                        task_done()
                        self._poll_queue.put(task)
                        break

                # build a query string with ids of all futures in this frame
                ids = [future.id for future in frame_futures.values()]
                _LOGGER.debug("Polling for status of futures: %s", ids)
                query_string = 'problems/?id=' + ','.join(ids)

                # if futures were cancelled while `add`ing, skip empty frame
                if not ids:
                    continue

                # wait until `frame_earliest` before polling
                delay = frame_earliest - time.time()
                if delay > 0:
                    _LOGGER.debug("Pausing polling %.2f sec for futures: %s", delay, ids)
                    time.sleep(delay)
                else:
                    _LOGGER.trace("Skipping non-positive delay of %.2f sec", delay)

                try:
                    _LOGGER.trace("Executing poll API request")

                    try:
                        response = self.session.get(posixpath.join(self.endpoint, query_string))
                    except requests.exceptions.Timeout:
                        raise RequestTimeout

                    if response.status_code == 401:
                        raise SolverAuthenticationError()
                    response.raise_for_status()

                    statuses = response.json()
                    for status in statuses:
                        self._handle_problem_status(status, frame_futures[status['id']])

                except BaseException as exception:
                    if not isinstance(exception, SolverAuthenticationError):
                        exception = IOError(exception)

                    for id_ in frame_futures.keys():
                        frame_futures[id_]._set_error(IOError(exception), sys.exc_info())

                for id_ in frame_futures.keys():
                    task_done()

                time.sleep(0)

        except Exception as err:
            _LOGGER.exception(err)
910139
def poll(self):
        """"""
        if self._subprocess is not None:
            self._subprocess.poll()

        time.sleep(self._beaver_config.get('subprocess_poll_sleep'))
799764
def run(self, timeout = 0):
        
        # poll timeout param is a integer number of miliseconds (seconds/1000).
        ptimeout = int(
            timeout.days * 86400000 +
            timeout.microseconds / 1000 +
            timeout.seconds * 1000
            if timeout else (self.m_resolution if timeout is None else 0)
        )
        if self.tokens:
            events = self.poller.poll(ptimeout)
            len_events = len(events)-1
            for nr, (fd, ev) in enumerate(events):
                act = self.shadow.pop(fd)
                if ev & POLLHUP:
                    self.poller.unregister(fd)
                    self.handle_error_event(act, 'Hang up.', ConnectionClosed)
                elif ev & POLLNVAL:
                    self.poller.unregister(fd)
                    self.handle_error_event(act, 'Invalid descriptor.')
                elif ev & POLLERR:
                    self.poller.unregister(fd)
                    self.handle_error_event(act, 'Unknown error.')
                else:
                    if nr == len_events:
                        ret = self.yield_event(act)
                        if ret:
                            self.poller.unregister(fd)
                        else:
                            self.shadow[fd] = act
                        return ret
                    else:
                        if self.handle_event(act):
                            self.poller.unregister(fd)
                        else:
                            self.shadow[fd] = act

        else:
            sleep(timeout)
1135927
function shutdown() {
		var timer

		for (var id in requests)
			if (timer = requests[id].timer) {
				clearTimeout(timer)
				requests[id].timer = null
			}
	}
125890
async def shutdown(self, timeout: Optional[float]=15.0) -> None:
        """"""
        self._force_close = True

        if self._keepalive_handle is not None:
            self._keepalive_handle.cancel()

        if self._waiter:
            self._waiter.cancel()

        # wait for handlers
        with suppress(asyncio.CancelledError, asyncio.TimeoutError):
            with CeilTimeout(timeout, loop=self._loop):
                if (self._error_handler is not None and
                        not self._error_handler.done()):
                    await self._error_handler

                if (self._task_handler is not None and
                        not self._task_handler.done()):
                    await self._task_handler

        # force-close non-idle handler
        if self._task_handler is not None:
            self._task_handler.cancel()

        if self.transport is not None:
            self.transport.close()
            self.transport = None
1309050
function pollDo(fn, timeOut, doName, obj) {
  var siv = null;

  if (!obj) {
    obj = window;
  }
  if (timeOut == null) {
    timeOut = 100;
  }

  //If the previous poll operation is exist,then make it cancel.
  if (doName && obj[doName]) {
    clearInterval(obj[doName]);
  }

  //Polling execution operations every interval a period of time.
  siv = setInterval(function () {
    if (fn.call(obj) === false) {
      clearInterval(siv);
    }
  }, timeOut);

  if (doName) {
    obj[doName] = siv;
  }

  return siv;
}
727753
def _run_forever(self):
        
        while True:
            try:
                tick = time.time()

                asyncore.loop(timeout=self.POLL_TIMEOUT, use_poll=True)

                # Sleep for remaining poll cycle time
                tick += self.POLL_TIMEOUT - time.time()
                if tick > 0:
                    # wait POLL_TIMEOUT at most (robust against time shifts)
                    time.sleep(min(tick, self.POLL_TIMEOUT))
            except KeyboardInterrupt as exc:
                self.LOG.info("Termination request received (%s)" % exc)
                break
            except SystemExit as exc:
                self.return_code = exc.code or 0
                self.LOG.info("System exit (RC=%r)" % self.return_code)
                break
            else:
                # Idle work
                #self.LOG.warn("IDLE %s %r" % (self.options.guard_file, os.path.exists(self.options.guard_file)))
                if self.options.guard_file and not os.path.exists(self.options.guard_file):
                    self.LOG.warn("Guard file '%s' disappeared, exiting!" % self.options.guard_file)
                    break
893941
def stop(self, timeout=5):
        
        # Must shut down threads here so the code that calls
        # this method can know when all threads are stopped.
        for worker in self._threads:
            self._queue.put(_SHUTDOWNREQUEST)

        # Don't join currentThread (when stop is called inside a request).
        current = threading.currentThread()
        if timeout is not None and timeout >= 0:
            endtime = time.time() + timeout
        while self._threads:
            worker = self._threads.pop()
            if worker is not current and worker.isAlive():
                try:
                    if timeout is None or timeout < 0:
                        worker.join()
                    else:
                        remaining_time = endtime - time.time()
                        if remaining_time > 0:
                            worker.join(remaining_time)
                        if worker.isAlive():
                            # We exhausted the timeout.
                            # Forcibly shut down the socket.
                            c = worker.conn
                            if c and not c.rfile.closed:
                                try:
                                    c.socket.shutdown(socket.SHUT_RD)
                                except TypeError:
                                    # pyOpenSSL sockets don't take an arg
                                    c.socket.shutdown()
                            worker.join()
                except (
                    AssertionError,
                    # Ignore repeated Ctrl-C.
                    # See
                    # https://github.com/cherrypy/cherrypy/issues/691.
                    KeyboardInterrupt,
                ):
                    pass
37798
@Override
    public V pollFromAny(long timeout, TimeUnit unit, String... queueNames) throws InterruptedException {
        return blockingQueue.pollFromAny(timeout, unit);
    }
17991
def shutdown(server, graceful=True):
    
    ioloop = IOLoop.instance()

    logging.info("Stopping server...")
    # Stop listening for new connections
    server.stop()

    def final_stop():
        ioloop.stop()
        logging.info("Stopped.")
        sys.exit(0)

    def poll_stop(counts={'remaining': None, 'previous': None}):
        remaining = len(ioloop._handlers)
        counts['remaining'], counts['previous'] = remaining, counts['remaining']
        previous = counts['previous']
        # Wait until we only have only one IO handler remaining.  That
        # final handler will be our PeriodicCallback polling task.
        if remaining == 1:
            final_stop()
        if previous is None or remaining != previous:
            logging.info("Waiting on IO %d remaining handlers", remaining)

    if graceful:
        # Callback to check on remaining handlers.
        poller = PeriodicCallback(poll_stop, 250, io_loop=ioloop)
        poller.start()

        # Give up after 10 seconds of waiting.
        ioloop.add_timeout(time.time() + 10, final_stop)
    else:
        final_stop()
1054581
def _blocking_poll(self, timeout=None):
        
        if self._result_set:
            return

        retry_ = self._retry.with_deadline(timeout)

        try:
            retry_(self._done_or_raise)()
        except exceptions.RetryError:
            raise concurrent.futures.TimeoutError(
                "Operation did not complete within the designated " "timeout."
            )