in CBL_Replicator.m
- (void) retryIfReady
502876
protected void retryIfReady() {
        Log.v(Log.TAG_SYNC, "[retryIfReady()] stateMachine => " + stateMachine.getState().toString());
        // check if state is still IDLE (ONLINE), then retry now.
        if (stateMachine.getState().equals(ReplicationState.IDLE)) {
            Log.v(Log.TAG_SYNC, "%s RETRYING, to transfer missed revisions...", this);
            cancelRetryFuture();
            retry();
        }
    }
1073811
def wait_for_any_cluster(contexts):
    
    try:
        earliest_retry_at = min(ctx.retry_at for ctx in contexts.values()
                                if not ctx.failed)
    except ValueError:  # can't take min() of empty sequence
        raise AllClustersFailedException(
            "Could not find appropriate cluster for worker build."
        )

    time_until_next = earliest_retry_at - dt.datetime.now()
    time.sleep(max(timedelta(seconds=0), time_until_next).seconds)
743677
def __send_ready_cb(self, last_send_failure_time):
        """"""
        logger.debug('Readiness notification (last failed=%s)', last_send_failure_time)
        # It is possible for multiple timers to be scheduled (if multiple transport failures happen in a fairly short
        # amount of time. See logic for __send_retry_requests
        if last_send_failure_time is not None:
            self.__send_retry_requests_timer.cancel()
            # allow 10s for responses to come in before attempting to resend
            self.__send_retry_requests_timer = Timer(10, self.__send_retry_requests, args=(last_send_failure_time,))
            self.__send_retry_requests_timer.start()
167843
private void doWait( int currentTries, long optDuration_ms )
    {
        if ( optDuration_ms < 0 ) {
            optDuration_ms = ( long ) ( firstSleep_ms * ( Math.random() + 0.5 ) * ( 1L << ( currentTries - 1 ) ) );
        }

        LOGGER.debug( "Will retry request after {} millis", optDuration_ms );

        try {
            Thread.sleep( optDuration_ms );
        } catch ( InterruptedException ex ) {
            throw new CStorageException( "Retry waiting interrupted", ex );
        }
    }
125225
def mongo_retry(f):
    
    log_all_exceptions = 'arctic' in f.__module__ if f.__module__ else False

    @wraps(f)
    def f_retry(*args, **kwargs):
        global _retry_count, _in_retry
        top_level = not _in_retry
        _in_retry = True
        try:
            while True:
                try:
                    return f(*args, **kwargs)
                except (DuplicateKeyError, ServerSelectionTimeoutError) as e:
                    # Re-raise errors that won't go away.
                    _handle_error(f, e, _retry_count, **_get_host(args))
                    raise
                except (OperationFailure, AutoReconnect) as e:
                    _retry_count += 1
                    _handle_error(f, e, _retry_count, **_get_host(args))
                except Exception as e:
                    if log_all_exceptions:
                        _log_exception(f.__name__, e, _retry_count, **_get_host(args))
                    raise
        finally:
            if top_level:
                _in_retry = False
                _retry_count = 0
    return f_retry
945286
def retry(tries, CatchExceptions=(Exception,), delay=0.01, backoff=2):
    '''
    

    '''
    if backoff <= 1:
        raise ValueError("backoff must be greater than 1")

    if tries < 0:
        raise ValueError("tries must be 0 or greater")

    if delay <= 0:
        raise ValueError("delay must be greater than 0")

    def deco_retry(f):
        @wraps(f)
        def f_retry(*args, **kwargs):
            mdelay = delay
            retException = None
            for mtries in range(tries):
                try:
                    return f(*args, **kwargs)
                except CatchExceptions as ex:
                    logger.warning(
                        "function %s(%s, %s) try %d times error: %s\n" % (f.__name__, args, kwargs, mtries, str(ex)))
                    logger.warning("Retrying in %.4f seconds..." % (mdelay))

                    retException = ex
                    time.sleep(mdelay)
                    mdelay *= backoff
            raise retException

        return f_retry

    return deco_retry
72310
<T> T callWithRetries(Callable<T> callable, RecurringPolicy<?> recurringPolicy,
      RecurringStats retryStats, Set<Class<? extends Exception>> retryableExceptions,
      boolean recoverable, boolean logFailures) throws Exception {
    boolean recovery = retryStats != null;

    while (true) {
      try {
        return callable.call();
      } catch (Exception e) {
        ShutdownSignalException sse = extractCause(e, ShutdownSignalException.class);
        if (sse == null && logFailures && recurringPolicy != null
            && recurringPolicy.allowsAttempts())
          log.error("Invocation of {} failed.", callable, e);

        if (sse != null && (recovery || !recoverable))
          throw e;

        if (!closed) {
          try {
            // Retry on channel recovery failure or retryable exception
            boolean retryable =
                recurringPolicy != null && recurringPolicy.allowsAttempts()
                    && isRetryable(retryableExceptions, e, sse);
            long startTime = System.nanoTime();

            if (retryable) {
              if (retryStats == null) 
                retryStats = new RecurringStats(recurringPolicy);
                
              // Wait for pending recovery
              if (sse != null) {
                if (recurringPolicy.getMaxDuration() == null)
                  circuit.await();
                else if (!circuit.await(retryStats.getMaxWaitTime())) {
                  log.debug("Exceeded max wait time while waiting for {} to recover", this);
                  throw e;
                }
              }

              // Continue retries
              retryStats.incrementAttempts();
              if (!retryStats.isPolicyExceeded()) {
                long remainingWaitTime =
                    retryStats.getWaitTime().toNanos() - (System.nanoTime() - startTime);
                if (remainingWaitTime > 0)
                  retryWaiter.await(Duration.nanos(remainingWaitTime));
                continue;
              }
            }
          } catch (Throwable ignore) {
          }
        }

        throw e;
      }
    }
  }
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
715908
def retry(self):
    
    path = self._path() + '/retry'
    resp = self._get_resource_root().post(path)
    return ApiCommand.from_json_dict(resp, self._get_resource_root())
586909
async def retry_async(self, func, partition_id, retry_message,
                          final_failure_message, max_retries, host_id):
        
        created_okay = False
        retry_count = 0
        while not created_okay and retry_count <= max_retries:
            try:
                await func(partition_id)
                created_okay = True
            except Exception as err:  # pylint: disable=broad-except
                _logger.error("%r %r %r %r", retry_message, host_id, partition_id, err)
                retry_count += 1
        if not created_okay:
            raise Exception(host_id, final_failure_message)
88340
private void retry(String subTaskSpecId, MonitorEntry monitorEntry, TaskStatusPlus lastFailedTaskStatus)
  {
    synchronized (startStopLock) {
      if (running) {
        final SubTaskSpec<T> spec = monitorEntry.spec;
        final T task = spec.newSubTask(monitorEntry.taskHistory.size() + 1);
        log.info("Submitting a new task[%s] for retrying spec[%s]", task.getId(), spec.getId());
        indexingServiceClient.runTask(task);
        incrementNumRunningTasks();

        runningTasks.put(
            subTaskSpecId,
            monitorEntry.withNewRunningTask(
                task,
                indexingServiceClient.getTaskStatus(task.getId()).getStatus(),
                lastFailedTaskStatus
            )
        );
      }
    }
  }
401144
function retry(fn) {

  return function retried() {

    var args = arguments.length ? Array.prototype.slice.call(arguments, 0, arguments.length - 1) : [];
    var done = arguments.length ? arguments[arguments.length - 1] : noop;

    var cfn = null;
    var canceled = false;

    function exec() {
      var err = arguments[0];
      if (!err || canceled) {
        done.apply(null, arguments);
      } else {
        cfn = fn.apply(null, args);
      }
    }

    args.push(exec);
    exec(true);

    return function cancel() {
      canceled = true;
      cfn.apply(null, arguments);
    };

  };

}
1254657
def retry_on_excs(excs, retry_count=3, delay=5):
    

    def wrapper(f):
        @functools.wraps(f)
        def deco(*args, **kwargs):
            for i in range(0, retry_count):
                try:
                    return f(*args, **kwargs)
                except excs:
                    if logger:
                        logger.warning(
                            'HTTPError caught.Retrying ...'.format(f.__name__),
                            exc_info=True
                        )
                    time.sleep(delay)
            else:
                logger.error(
                    '{} failed after {} retries'.format(
                        f.__name__, retry_count)
                )
            return f(*args, **kwargs)

        return deco

    return wrapper
689812
def retrier(*, max_attempts, sleeptime, max_sleeptime, sleepscale=1.5, jitter=0.2):
  
  assert(max_attempts > 1)
  assert(sleeptime >= 0)
  assert(0 <= jitter <= sleeptime)
  assert(sleepscale >= 1)

  cur_sleeptime = min(max_sleeptime, sleeptime)

  for attempt in range(max_attempts):
    cur_jitter = random.randint(int(-jitter * 1000), int(jitter * 1000)) / 1000
    yield max(0, cur_sleeptime + cur_jitter)
    cur_sleeptime = min(max_sleeptime, cur_sleeptime * sleepscale)
17783
def retry(self):
        """"""
        self.state = STATE_STARTING
        self.loop.call_later(RETRY_TIMER, self.start)
        _LOGGER.debug('Reconnecting to deCONZ in %i.', RETRY_TIMER)
1120806
def calculate_retry_delay(attempt, max_delay=300):
    """"""
    delay = int(random.uniform(2, 4) ** attempt)
    if delay > max_delay:
        # After reaching the max delay, stop using expontential growth
        # and keep the delay nearby the max.
        delay = int(random.uniform(max_delay - 20, max_delay + 20))
    return delay
156519
public static void retryOrCancel(final CoreEnvironment environment, final CouchbaseRequest request,
        final EventSink<ResponseEvent> responseBuffer) {
        if (!request.isActive()) {
            return;
        }

        if (environment.retryStrategy().shouldRetry(request, environment)) {
            retry(request, responseBuffer);
        } else {
            request.observable().onError(new RequestCancelledException("Could not dispatch request, cancelling "
                + "instead of retrying."));
        }
    }