PHP code example of gohany / rtry

1. Go to this page and download the library: Download gohany/rtry 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/ */

    

gohany / rtry example snippets


use Gohany\Rtry\Impl\Retry;
use Gohany\Rtry\Impl\RtryPolicyFactory;

// Build a policy from a string spec:
$factory = new RtryPolicyFactory();
$policy  = $factory->fromSpec('rtry:a=5;d=200;mode=exp;b=2;cap=8s;j=100@full;on=5xx,ETIMEDOUT');

$retry = new Retry(); // uses default Clock and Sleeper; no logger by default
$result = $retry->try(function () {
    // Your flaky operation (HTTP call, DB query, etc)
    return 'ok';
}, $policy);

use Gohany\Rtry\Impl\Parts\Sequence;

// Accepts multiple forms:
Sequence::make('50,100,1.5s*');
Sequence::make('(50,100ms,1.5s*)');
Sequence::make('seq=(50,100,1.5s,*)');

// Canonical string form:
(string) Sequence::make('50,100,1.5s*'); // "seq=(50,100,1.5s*)"

// '*' means repeat the last delay indefinitely.

$retry->setBetweenAttemptsHook(function (
    \Gohany\Retry\AttemptContextInterface $ctx,
    \Gohany\Retry\AttemptOutcomeInterface $outcome,
    \Gohany\Retry\RetryPolicyInterface $policy,
    int $sleepMs,
    array $lastHeaders
) {
    // observe sleep decision, metrics, logging, etc.
});

$retry->setOnGiveUpHook(function ($ctx, $outcome, $policy, $headers) {
    // after the final failure before giving up
});

$spec = 'rtry:a5;seq=50,100,200,400,800*;j=20%@pm';
$policy = (new RtryPolicyFactory())->fromSpec($spec);
$result = (new Retry())->try(fn() => $client->get($url), $policy);

$policy = (new RtryPolicyFactory())->fromSpec('rtry:a=1;h=3@75');
$retry = new Retry();
$resp  = $retry->try(fn() => $client->get($url), $policy);

use Gohany\Rtry\Impl\Deciders\CompositeDecider;
use Gohany\Rtry\Impl\Deciders\OnTokensDecider;

$spec = 'rtry:a5;seq=50,100*;j=20%@pm;on=4xx,5xx,NETWORK_ERROR,RATE_LIMITED';
$policy = (new RtryPolicyFactory())->fromSpec($spec);
$retry = new Retry();
$resp  = $retry->try(fn() => $client->get($url), $policy);