PHP code example of jord-jd / attempt

1. Go to this page and download the library: Download jord-jd/attempt library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jord-jd / attempt example snippets


$result = attempt(function () {
    return fetchFromAnUnreliableApi();
})
    ->maxAttempts(5)
    ->withGap(2)
    ->now();

$result = attempt($operation)
    ->maxAttempts(5)
    ->withExponentialBackoff(1, 2.0, 30)
    ->now();

use Exception;

$result = attempt($operation)
    ->withBackoff(function (int $failedAttempt, Exception $exception): int {
        return min(60, $failedAttempt * 5);
    })
    ->now();

$result = attempt($operation)
    ->retryIf(function (Exception $exception, int $failedAttempt): bool {
        return $exception instanceof TemporaryApiException;
    })
    ->maxAttempts(5)
    ->now();

attempt($operation)
    ->onRetry(function (Exception $exception, int $failedAttempt, int $delay): void {
        logger()->warning('Operation failed; retrying', [
            'attempt' => $failedAttempt,
            'delay' => $delay,
            'exception' => $exception,
        ]);
    })
    ->now();

// Retry until this instant. No execution is started at or after the deadline.
attempt($operation)
    ->until(new DateTimeImmutable('+30 seconds'))
    ->withGap(5)
    ->now();

// Wait until this instant, then begin. A past time starts immediately.
attempt($operation)
    ->at(new DateTimeImmutable('+5 seconds'));