Retry this factory's connection. It is assumed that a previous
        connection was attempted and failed- either before or after a
        successful connection.
282
def retry(self):
        

        if self.connector is None:
            raise ValueError("No connector to retry")
        if self.service is None:
            return
        self.connector.connect()
123502
def is_error_retryable(request, exc):
    
    if is_last_attempt(request):
        return False

    return (
        isinstance(exc, RetryableException)
        or IRetryableError.providedBy(exc)
    )
473711
def _call_retry(self, force_retry):
        """"""
        last_exception = None
        for i in range(self.max_attempts):
            try:
                log.info("Calling %s %s" % (self.method, self.url))
                response = self.requests_method(
                    self.url,
                    data=self.data,
                    params=self.params,
                    headers=self.headers,
                    timeout=(self.connect_timeout, self.read_timeout),
                    verify=self.verify_ssl,
                )

                if response is None:
                    log.warn("Got response None")
                    if self._method_is_safe_to_retry():
                        delay = 0.5 + i * 0.5
                        log.info("Waiting %s sec and Retrying since call is a %s" % (delay, self.method))
                        time.sleep(delay)
                        continue
                    else:
                        raise PyMacaronCoreException("Call %s %s returned empty response" % (self.method, self.url))

                return response

            except Exception as e:

                last_exception = e

                retry = force_retry

                if isinstance(e, ReadTimeout):
                    # Log enough to help debugging...
                    log.warn("Got a ReadTimeout calling %s %s" % (self.method, self.url))
                    log.warn("Exception was: %s" % str(e))
                    resp = e.response
                    if not resp:
                        log.info("Requests error has no response.")
                        # TODO: retry=True? Is it really safe?
                    else:
                        b = resp.content
                        log.info("Requests has a response with content: " + pprint.pformat(b))
                    if self._method_is_safe_to_retry():
                        # It is safe to retry
                        log.info("Retrying since call is a %s" % self.method)
                        retry = True

                elif isinstance(e, ConnectTimeout):
                    log.warn("Got a ConnectTimeout calling %s %s" % (self.method, self.url))
                    log.warn("Exception was: %s" % str(e))
                    # ConnectTimeouts are safe to retry whatever the call...
                    retry = True

                if retry:
                    continue
                else:
                    raise e

        # max_attempts has been reached: propagate the last received Exception
        if not last_exception:
            last_exception = Exception("Reached max-attempts (%s). Giving up calling %s %s" % (self.max_attempts, self.method, self.url))
        raise last_exception
588592
def retry(self, delay=0, group=None, message=None):
        ''''''
        args = ['retry', self.jid, self.queue_name, self.worker_name, delay]
        if group is not None and message is not None:
            args.append(group)
            args.append(message)
        return self.client(*args)
518737
def try_again_later(self, seconds):
        """"""
        if not self.failed:
            self.fails += 1
            self.retry_at = (dt.datetime.now() + timedelta(seconds=seconds))
459908
def reconnect(self, conn_retries=None):
        '''  '''
        if conn_retries is None:
            conn_retries = self.conn_retries

        count = 0
        if self.logger:
            self.logger.info('Connecting to Redis..')
        while count < conn_retries:
            super(redis.client.Redis, self).__init__(*self.args, **self.kwargs)

            if self.ping():
                if self.logger:
                    self.logger.info('Connected to Redis!')
                return True
            else:
                sl = min(3 ** count, self.max_sleep)
                if self.logger:
                    self.logger.info('Connecting failed, retrying in {0} seconds'.format(sl))
                time.sleep(sl)
                count += 1
        raise ConnectionError
970821
public boolean canTryToConnect(int retryAfterSecend) {
        // 如果是有效连接
        if (this.available) {
            return true;
            // 如果连接无效，并且达到重试时间
        } else if ((System.currentTimeMillis() - lastUnavailableTime) > retryAfterSecend * 1000) {
            return true;
        }
        return false;
    }
1287232
def connect_with_retry(self) -> None:
        
        if self.is_connected():
            log.debug('Already connected to the Slack API')
            return

        for retry in range(1, self.retries + 1):
            self.connect()
            if self.is_connected():
                log.debug('Connected to the Slack API')
                return
            else:
                interval = self.backoff(retry)
                log.debug("Waiting %.3fs before retrying", interval)
                time.sleep(interval)

        raise FailedConnection('Failed to connect to the Slack API')
840709
async def reconnect(self):
        """"""
        _LOGGER.debug('starting Connection.reconnect')
        await self._connect()
        while self._closed:
            await self._retry_connection()
        _LOGGER.debug('ending Connection.reconnect')
402247
def _reconnect_delay(self):
        
        if self.RECONNECT_ON_ERROR and self.RECONNECT_DELAYED:
            if self._reconnect_attempts >= len(self.RECONNECT_DELAYS):
                return self.RECONNECT_DELAYS[-1]
            else:
                return self.RECONNECT_DELAYS[self._reconnect_attempts]
        else:
            return 0
137807
def retry(retries=KAFKA_WAIT_RETRIES, delay=KAFKA_WAIT_INTERVAL,
          check_exceptions=()):
    """"""
    def decorator(func):
        """Decorator."""
        def f_retry(*args, **kwargs):
            """Retry running function on exception after delay."""
            for i in range(1, retries + 1):
                try:
                    return func(*args, **kwargs)
                # pylint: disable=W0703
                # We want to catch all exceptions here to retry.
                except check_exceptions + (Exception,) as exc:
                    if i < retries:
                        logger.info('Connection attempt %d of %d failed',
                                    i, retries)
                        if isinstance(exc, check_exceptions):
                            logger.debug('Caught known exception, retrying...',
                                         exc_info=True)
                        else:
                            logger.warn(
                                'Caught unknown exception, retrying...',
                                exc_info=True)
                    else:
                        logger.exception('Failed after %d attempts', retries)

                        raise

                # No exception so wait before retrying
                time.sleep(delay)

        return f_retry
    return decorator
271211
def retry(f, exc_classes=DEFAULT_EXC_CLASSES, logger=None,
          retry_log_level=logging.INFO,
          retry_log_message="Connection broken in '{f}' (error: '{e}'); "
                            "retrying with new connection.",
          max_failures=None, interval=0,
          max_failure_log_level=logging.ERROR,
          max_failure_log_message="Max retries reached for '{f}'. Aborting."):
    
    exc_classes = tuple(exc_classes)

    @wraps(f)
    def deco(*args, **kwargs):
        failures = 0
        while True:
            try:
                return f(*args, **kwargs)
            except exc_classes as e:
                if logger is not None:
                    logger.log(retry_log_level,
                               retry_log_message.format(f=f.func_name, e=e))
                gevent.sleep(interval)
                failures += 1
                if max_failures is not None \
                        and failures > max_failures:
                    if logger is not None:
                        logger.log(max_failure_log_level,
                                   max_failure_log_message.format(
                                       f=f.func_name, e=e))
                    raise
    return deco
335664
@Override
    public synchronized boolean checkConnection(final boolean forceReconnect) {
        if (checkConnection(conn)) {
            return true;
        } else if (forceReconnect) {
            try {
                connect();
                recover();

                return true;
            } catch (final Exception ex) {
                logger.debug(dev, "reconnection failure", ex);
                return false;
            }
        }

        return false;
    }
1257954
async def _reconnect(self, last_error):
        
        self._log.debug('Closing current connection...')
        await self._connection.disconnect()

        await helpers._cancel(
            self._log,
            send_loop_handle=self._send_loop_handle,
            recv_loop_handle=self._recv_loop_handle
        )

        # TODO See comment in `_start_reconnect`
        # Perhaps this should be the last thing to do?
        # But _connect() creates tasks which may run and,
        # if they see that reconnecting is True, they will end.
        # Perhaps that task creation should not belong in connect?
        self._reconnecting = False

        # Start with a clean state (and thus session ID) to avoid old msgs
        self._state.reset()

        retries = self._retries if self._auto_reconnect else 0
        for attempt in retry_range(retries):
            try:
                await self._connect()
            except (IOError, asyncio.TimeoutError) as e:
                last_error = e
                self._log.info('Failed reconnection attempt %d with %s',
                               attempt, e.__class__.__name__)

                await asyncio.sleep(self._delay)
            except Exception as e:
                last_error = e
                self._log.exception('Unexpected exception reconnecting on '
                                    'attempt %d', attempt)

                await asyncio.sleep(self._delay)
            else:
                self._send_queue.extend(self._pending_state.values())
                self._pending_state.clear()

                if self._auto_reconnect_callback:
                    self._loop.create_task(self._auto_reconnect_callback())

                break
        else:
            self._log.error('Automatic reconnection failed {} time(s)'
                            .format(attempt))
            await self._disconnect(error=last_error.with_traceback(None))
1246678
def _should_retry(self, context):
        # type: (ExponentialRetryWithMaxWait,
        #        azure.storage.common.models.RetryContext) -> bool
        
        # do not retry if max attempts equal or exceeded
        if context.count >= self.max_attempts:
            return False

        # get response status
        status = None
        if context.response and context.response.status:
            status = context.response.status

        # if there is no response status, then handle the exception
        # appropriately from the lower layer
        if status is None:
            exc = context.exception
            # default to not retry in unknown/unhandled exception case
            ret = False
            # requests timeout, retry
            if isinstance(exc, requests.Timeout):
                ret = True
            elif isinstance(exc, requests.exceptions.ContentDecodingError):
                ret = True
            elif (isinstance(exc, requests.exceptions.ConnectionError) or
                  isinstance(exc, requests.exceptions.ChunkedEncodingError)):
                # newer versions of requests do not expose errno on the
                # args[0] reason object; manually string parse
                if isinstance(exc.args[0], urllib3.exceptions.MaxRetryError):
                    try:
                        msg = exc.args[0].reason.args[0]
                    except (AttributeError, IndexError):
                        # unexpected/malformed exception hierarchy, don't retry
                        pass
                    else:
                        if any(x in msg for x in _RETRYABLE_ERRNO_MAXRETRY):
                            ret = True
                elif isinstance(exc.args[0], urllib3.exceptions.ProtocolError):
                    try:
                        msg = exc.args[0].args[0]
                    except (AttributeError, IndexError):
                        # unexpected/malformed exception hierarchy, don't retry
                        pass
                    else:
                        if any(x in msg for x in _RETRYABLE_ERRNO_PROTOCOL):
                            ret = True
            # fallback to string search
            if not ret:
                msg = str(exc).lower()
                if any(x in msg for x in _RETRYABLE_STRING_FALLBACK):
                    ret = True
            return ret
        elif 200 <= status < 300:
            # failure during respond body download or parsing, so success
            # codes should be retried
            return True
        elif 300 <= status < 500:
            # response code 404 should be retried if secondary was used
            if (status == 404 and
                    context.location_mode ==
                    azure.storage.common.models.LocationMode.SECONDARY):
                return True
            # response code 408 is a timeout and should be retried
            # response code 429 is too many requests (throttle)
            # TODO use "Retry-After" header for backoff amount
            if status == 408 or status == 429:
                return True
            return False
        elif status >= 500:
            # response codes above 500 should be retried except for
            # 501 (not implemented) and 505 (version not supported)
            if status == 501 or status == 505:
                return False
            return True
        else:  # noqa
            # this should be unreachable, retry anyway
            return True
1103785
def reconnect(self):
        
        # This is the old connection instance, stop its ioloop.
        self._connection.ioloop.stop()
        if self._running:
            # Create a new connection
            self.connect()
            # There is now a new connection, needs the new ioloop to run.
            self._connection.ioloop.start()
586072
def _try_reconnect(self):
        """"""

        try:
            if self.connection_interrupted:
                self.connect_direct(self.connection_string, force=True)
                self.connection_interrupted = False
                self.connected = True

                # Reenable streaming interface if that was open before as well
                if self._reports is not None:
                    self._loop.run_coroutine(self.adapter.open_interface(0, 'streaming'))

                # Reenable tracing interface if that was open before as well
                if self._traces is not None:
                    self._loop.run_coroutine(self.adapter.open_interface(0, 'tracing'))
        except HardwareError as exc:
            self._logger.exception("Error reconnecting to device after an unexpected disconnect")
            raise HardwareError("Device disconnected unexpectedly and we could not reconnect", reconnect_error=exc) from exc