Retry sending request until timeout or until receiving a response.
11150
def _make_request_to_server(self, query_function, raise_for_status=True,
                                time_limit_seconds=2, retry_delay_seconds=0.2):
        
        start_time = datetime.datetime.now()
        while datetime.datetime.now() - start_time < datetime.timedelta(
                0, time_limit_seconds):
            error = None
            response = None
            try:
                response = query_function()
            except requests.exceptions.ConnectionError as e:
                error = ServerConnectionError(
                    "No response from server.\n%s" % e)
            except:
                if response:
                    logger.info(response.text)
                raise
            if response is not None and raise_for_status:
                # raises requests.exceptions.HTTPError
                self._raise_for_status(response)
            if error:
                time.sleep(retry_delay_seconds)
                continue
            else:
                return response
        raise error
228996
def wait_for(self, timeout=3000):
        """"""
        results = [None]
        results_called = [False]

        def results_callback(val):
            results[0] = val
            results_called[0] = True

        self.then(results_callback)

        start = time.time()
        while not results_called[0]:
            if time.time() - start > timeout / 1000.:
                raise Exception('Timeout of %d ms reached' % timeout)
            ip.kernel.do_one_iteration()
        return results[0]
138770
void timeout() {
    long time = System.currentTimeMillis();
    Iterator<Map.Entry<Long, ContextualFuture>> iterator = responseFutures.entrySet().iterator();
    while (iterator.hasNext()) {
      ContextualFuture future = iterator.next().getValue();
      if (future.time + requestTimeout < time) {
        iterator.remove();
        future.context.executor().execute(() -> future.completeExceptionally(new TimeoutException("request timed out")));
      } else {
        break;
      }
    }
  }
141973
def _handle_request(self, request):
        """"""
        if 'types' in self.method_data[request['method']]:
            self._validate_params_types(request['method'], request['params'])

        if self.serve_exception:
            raise self.serve_exception()
        d = self._call_method(request)
        self.pending.add(d)
        if self.timeout:
            timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)

            def completed(result):
                if timeout_deferred.active():
                    # cancel the timeout_deferred if it has not been fired yet
                    # this is to prevent d's deferred chain from firing twice
                    # (and raising an exception).
                    timeout_deferred.cancel()
                return result
            d.addBoth(completed)
        try:
            result = yield d
        except defer.CancelledError:
            # The request was cancelled due to a timeout or by cancelPending
            # having been called. We return a TimeoutError to the client.
            self._remove_pending(d)
            raise TimeoutError()
        except Exception as e:
            self._remove_pending(d)
            raise e
        self._remove_pending(d)
        # Do not respond to notifications.
        if request['id'] is None:
            defer.returnValue(None)

        respond = {}
        self._fill_ver(request['jsonrpc'], respond)
        respond['result'] = result
        respond['id'] = request['id']

        defer.returnValue(respond)
1348541
def retry(tries=10, delay=1, backoff=2, retry_exception=None):
    
    assert tries > 0, "tries must be 1 or greater"
    catching_mode = bool(retry_exception)

    def deco_retry(f):
        @functools.wraps(f)
        def f_retry(*args, **kwargs):
            mtries, mdelay = tries, delay

            while mtries > 0:
                time.sleep(mdelay)
                mdelay *= backoff
                try:
                    rv = f(*args, **kwargs)
                    if not catching_mode and rv:
                        return rv
                except retry_exception:
                    pass
                else:
                    if catching_mode:
                        return rv
                mtries -= 1
                if mtries is 0 and not catching_mode:
                    return False
                if mtries is 0 and catching_mode:
                    return f(*args, **kwargs)  # extra try, to avoid except-raise syntax
                log.debug("{0} try, sleeping for {1} sec".format(tries-mtries, mdelay))
            raise Exception("unreachable code")
        return f_retry
    return deco_retry
368927
def timeout(self, timeout):
        """"""
        self._proxy_json._timeout = timeout
        self._proxy_http._timeout = timeout
68261
def listen_until_return(self, *temporary_handlers, timeout=0):
        """"""
        start = time.time()
        while timeout == 0 or time.time() - start < timeout:
            res = self.listen(*temporary_handlers)
            if res is not None:
                return res
912503
def retry(func):
    
    def retried_func(*args, **kwargs):
        max_tries = 3
        tries = 0
        while True:
            try:
                resp = func(*args, **kwargs)

            except requests.exceptions.ConnectionError as exc:
                exc.msg = "Connection error for session; exiting"
                raise exc

            except requests.exceptions.HTTPError as exc:
                exc.msg = "HTTP error for session; exiting"
                raise exc

            if resp.status_code != 200 and tries < max_tries:
                logger.warning("retrying request; current status code: {}"
                               .format(resp.status_code))
                tries += 1
                # mini exponential backoff here.
                time.sleep(tries ** 2)
                continue

            break

        if resp.status_code != 200:
            error_message = resp.json()["error"]["message"]
            logger.error("HTTP Error code: {}: {}".format(resp.status_code, error_message))
            logger.error("Rule payload: {}".format(kwargs["rule_payload"]))
            raise requests.exceptions.HTTPError

        return resp

    return retried_func
542898
public boolean waitForResponse ()
        throws TimeoutException
    {
        if (_success == 0) {
            synchronized (this) {
                try {
                    // wait for the response, timing out after a while
                    if (_timeout == NO_TIMEOUT) {
                        wait();

                    } else {
                        wait(1000L * _timeout);
                    }
                    // if we get here without some sort of response, then we've timed out
                    if (_success == 0) {
                        throw new TimeoutException();
                    }

                } catch (InterruptedException ie) {
                    throw (TimeoutException)
                        new TimeoutException().initCause(ie);
                }
            }
        }

        return (_success > 0);
    }
1063348
def wait_response(self):
        ''''''
        responses = self.read()
        while not responses:
            responses = self.read()
        return responses
123236
function retry(err) {
    if (currentAttempt >= retryCount) {
      return callback(err, null, currentAttempt);
    }

    currentAttempt += 1;

    // Since the currentAttempt starts at 1 and it was just incremented
    // currentAttempt - 2 will be the actual timeout index.
    return setTimeout(attempt, timeouts[currentAttempt - 2]);
  }
962658
def make_request(self, handle, value, timeout=DEFAULT_TIMEOUT, with_response=True):
        """"""
        try:
            with self:
                _LOGGER.debug("Writing %s to %s with with_response=%s", codecs.encode(value, 'hex'), handle, with_response)
                self._conn.writeCharacteristic(handle, value, withResponse=with_response)
                if timeout:
                    _LOGGER.debug("Waiting for notifications for %s", timeout)
                    self._conn.waitForNotifications(timeout)
        except btle.BTLEException as ex:
            _LOGGER.debug("Got exception from bluepy while making a request: %s", ex)
            raise
918673
def _send_and_wait(self, **kwargs):
        
        frame_id = self.next_frame_id
        kwargs.update(dict(frame_id=frame_id))
        self._send(**kwargs)
        timeout = datetime.now() + const.RX_TIMEOUT
        while datetime.now() < timeout:
            try:
                frame = self._rx_frames.pop(frame_id)
                raise_if_error(frame)
                return frame
            except KeyError:
                sleep(0.1)
                continue
        _LOGGER.exception(
            "Did not receive response within configured timeout period.")
        raise exceptions.ZigBeeResponseTimeout()
120182
def send_and_wait(self, path, message, timeout=0, responder=None):
        

        message.on("response", lambda x,event_origin,source:None, once=True)

        if timeout > 0:
            ts = time.time()
        else:
            ts = 0
        sent = False

        while not message.response_received:
            if not sent:
                self.send(path, message)
                sent = True
            if ts:
                if time.time() - ts > timeout:
                    raise exceptions.TimeoutError("send_and_wait(%s)"%path, timeout)

        return message.response_message
181401
@Override
  public void retry(VolleyError error) throws VolleyError {
    currentRetryCount++;
    currentTimeoutMs += (currentTimeoutMs * backoffMultiplier);
    if (!hasAttemptRemaining()) {
      throw error;
    }
  }
163089
def _wait_for_request(self, uuid, connection_adapter=None):
        
        start_time = time.time()
        while not self._response[uuid]:
            connection_adapter.check_for_errors()
            if time.time() - start_time > self._timeout:
                self._raise_rpc_timeout_error(uuid)
            time.sleep(IDLE_WAIT)
919864
def retry_until_not_none_or_limit_reached(method, limit, sleep_s=1,
                                          catch_exceptions=()):
  """"""
  return retry_until_valid_or_limit_reached(
      method, limit, lambda x: x is not None, sleep_s, catch_exceptions)