The retry function attempts to execute the given callback until the given maximum attempt threshold is met. If the callback does not throw an exception, its return value will be returned. If the callback throws an exception, it will automatically be retried. If the maximum attempt count is exceeded, the exception will be thrown
function retry($times, callable $callback, $sleep = 0, $when = null);
return retry(3, function ($attempts) {
// Attempt 3 times while resting 1000ms in between attempts...
echo "Try: {$attempts} " . now()->toTimeString() . PHP_EOL;
Throw new \Exception("Failed");
}, 1000);
/*
Try: 1 10:57:48 Try: 2 10:57:49 Try: 3 10:57:50
Exception Failed
*/
with callback function true
return retry(3, function ($attempts) {
// Attempt 3 times while resting 1000ms in between attempts...
echo "Try: {$attempts} " . now()->toTimeString() . PHP_EOL;
Throw new \Exception("Failed");
}, 1000, function(){
return true;
});
/*
Try: 1 10:57:48 Try: 2 10:57:49 Try: 3 10:57:50
Exception Failed
*/
with callback function false
return retry(3, function ($attempts) {
// Attempt 3 times while resting 1000ms in between attempts...
echo "Try: {$attempts} " . now()->toTimeString() . PHP_EOL;
Throw new \Exception("Failed");
}, 1000, function(){
return false;
});
/*
Try: 1 11:08:15
Exception Failed
*/
It can be used in real life with Http client
$response = retry(3, function () {
return Http::get('http://example.com/users/1');
}, 200)
Retry in the Http client
$response = Http::retries(3, 200)->get('http://example.com/users/1');
I hope you enjoy the code.
Top comments (0)