PHP code example of fostam / retry

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

    

fostam / retry example snippets


try {
    // sleep 1 second between attempts
    $funcResult = Retry::onFailure('myfunc', 3, new ConstantDelayPolicy(1000));
}
catch (RetryLimitException $e) {
    // failed after maximum number of attempts
}

// success before maximum number of attempts have been exceeded

$password = 'secret';
Retry::onCondition('getInput', function($result) use ($password) {
    return $result === $password;
}, 3);

private function multiply($a, $b) {
    return $a * $b;
}

...

$x = 3;
$y = 4;
Retry::onFailure(function() use ($x, $y) {
    return $this->multiply($x, $y);
}, 3);

// sleep 2000 milliseconds (i.e. 2 seconds) between attempts
$policy = new ConstantDelayPolicy(2000);

// sleep 1 second after the first, 2 after the second, 3 after the third...
$policy = new LinearDelayPolicy(1000);

// sleep 1, 2, 4, 8, 16, ...
$policy = new ExponentialDelayPolicy(1000);

// sleep 1, 3, 9, 27, ...
$policy = new ExponentialDelayPolicy(1000, 3);

// sleep 2, 2, 4, 20, 20, 20, 20 ... (stick to last value after series has ended)
$policy = new SeriesDelayPolicy([2000, 2000, 4000, 20000]);

// sleep 2, 2, 4, 20, 2, 2, 4, 20, 2, 2, 4, ... (repeat series after it has ended)
$policy = new SeriesDelayPolicy([2000, 2000, 4000, 20000], true);

// sleep a random amount between 1900 and 2100 milliseconds
$policy = new JitterDelayPolicy(2000, 100);

// don't sleep at all
$policy = new NoneDelayPolicy();

// retry without delay
Retry::onFailure('myfunc', 3);

Retry::onFailure('myfunc', 3, null, $tries);
print "success after {$tries} attempts";