/* Exponential sleep on failed request
Up to three retries will occur if first reqest fails
after 1.0 second, 2.2 seconds, and finally 7.0 seconds
@param retries current retry
@throws Exception if maximum number of retries has been reached
344598
private function pauseOnRetry($retries, $status)
    {
        if ($retries <= self::MAX_ERROR_RETRY) {
            // PHP delays are in microseconds (1 million microsecond = 1 sec)
            // 1st delay is (4^1) * 100000 + 600000 = 0.4 + 0.6 second = 1.0 sec
            // 2nd delay is (4^2) * 100000 + 600000 = 1.6 + 0.6 second = 2.2 sec
            // 3rd delay is (4^3) * 100000 + 600000 = 6.4 + 0.6 second = 7.0 sec
            $delay = (int) (pow(4, $retries) * 100000) + 600000;
            usleep($delay);
        } else {
            throw new \Exception('Error Code: '. $status.PHP_EOL.'Maximum number of retry attempts - '. $retries .' reached');
        }
    }
49928
private function _pauseOnRetry($retries)
    {
        if ($retries <= $this->_config['MaxErrorRetry']) {
            $delay = (int) (pow(4, $retries) * 100000);
            usleep($delay);
            return true;
        } 
        return false;
    }
1248243
@SuppressWarnings("unchecked")
	@Override
	public T retry(final int count, final int waitTime) {
		context().setMaxRetryCount(count).setRetryWaitTime(waitTime);
		return (T) this;
	}
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]);
  }
1163586
public Response reliableRequest(final Request request, final int[] retryCodes, int retries,
                                    final long delayMillis) {
        lastRequest = request;
        Response response = null;
        while (retries > 0) {
            response = makeRequest(request);

            if (!shouldRetry(response, retryCodes)) {
                break;
            }

            try {
                Thread.sleep(delayMillis);
            } catch (final InterruptedException e) {
                // Delay failed, continue
            }

            // Decrement retries
            retries--;
        }

        lastResponse = response;

        return response;
    }
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
1187385
public static <T> ComposableFuture<T> retry(final int retries, final FutureAction<T> action) {
    return retry(retries, __ -> action.execute());
  }
1008833
def execute_with_retries(retryable_function,
                         retryable_errors,
                         logger,
                         human_readable_action_name='Action',
                         nonretryable_errors=None):
    
    max_retries = 10
    attempt = 0
    if not nonretryable_errors:
        nonretryable_errors = ()
    while True:
        try:
            return retryable_function()
        except tuple(nonretryable_errors):
            raise
        except tuple(retryable_errors) as e:
            attempt += 1
            if attempt > max_retries:
                raise
            # Exponentional backoff on retry delay as suggested by
            # https://cloud.google.com/storage/docs/exponential-backoff
            delay = 2**attempt + random.random()
            logger.info('"%s" failed with error "%s". '\
                        'Retry number %s of %s in %s seconds'
                        % (human_readable_action_name, str(e),
                           attempt, max_retries, delay))
            time.sleep(delay)
533334
def retry(max_retries=1):
    

    def retry_func(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            num_retries = 0
            while num_retries <= max_retries:
                try:
                    ret = func(*args, **kwargs)
                    break
                except HTTPError:
                    if num_retries == max_retries:
                        raise
                    num_retries += 1
                    time.sleep(5)
            return ret

        return wrapper

    return retry_func
1158802
@Override
    public void retry(JusError error) throws JusError {
        if(errorFilter != null && !errorFilter.apply(error)) {
            throw error;
        }
        mCurrentRetryCount++;
        currentTimeoutMs = (int) (currentTimeoutMs * backoffMultiplier);
        if (!hasAttemptRemaining()) {
            throw error;
        }
    }
380005
public static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            JMExceptionManager.handleException(log, e, "sleep", millis);
        }
    }
1147703
public void setMaxRetriesOnIOError(int retries) {
        if (retries < 0) {
            throw new IllegalArgumentException("Parameter retries must be greater or equal to zero.");
        }

        HttpMethodRetryHandler retryHandler = new DefaultHttpMethodRetryHandler(retries, false);
        client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
        clientViaProxy.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
    }
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;
      }
    }
  }
364141
public static RetryPolicy defaultClientRetry(Duration maxRetryDuration, Duration baseSleepMs,
      Duration maxSleepMs) {
    return ExponentialTimeBoundedRetry.builder()
        .withMaxDuration(maxRetryDuration)
        .withInitialSleep(baseSleepMs)
        .withMaxSleep(maxSleepMs)
        .build();
  }
1132954
def execute_with_retries(self, action, f):
        
        # Run action until either it succeeds or throws an exception
        # that's not an ActionRetryException
        retry = True
        while retry:
            retry = False
            try:
                f(action)
            except ActionRetryException as ex:  # other exceptions should bubble out
                retry = True
                time.sleep(ex.ms_backoff / 1000.0)
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)
213787
public void run() throws Exception {
        // Send the initial command:
        client.sendRequest(cmd);

        long endTime = System.currentTimeMillis() + spec.getMaxDuration();

        // Wait until the 'after' time
        Thread.sleep(spec.getAfter());

        int numAttempts = 0;
        long now = System.currentTimeMillis();

        while (now < endTime) {
            client.sendRequest(cmd);
            now = System.currentTimeMillis();

            numAttempts ++;

            // See how to retry:
            long sleepTime = 0;
            if (spec.isConstant()) {
                sleepTime = spec.getInterval();
            } else if (spec.isLinear()) {
                sleepTime = spec.getInterval() * numAttempts;
            } else if (spec.isExponential()) {
                sleepTime = (long) Math.pow(spec.getInterval(), numAttempts);
            }

            if (spec.getCeil() > 0) {
                sleepTime = Math.min(spec.getCeil(), sleepTime);
            }

            if (now + sleepTime > endTime) {
                break;
            } else {
                accuSleep(sleepTime);
                now = System.currentTimeMillis();
            }
        }
    }