DEV Community

Morcos Gad
Morcos Gad

Posted on

retry method in laravel

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);
Enter fullscreen mode Exit fullscreen mode
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
*/
Enter fullscreen mode Exit fullscreen mode

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
*/
Enter fullscreen mode Exit fullscreen mode

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
*/
Enter fullscreen mode Exit fullscreen mode

It can be used in real life with Http client

$response = retry(3, function () {
    return Http::get('http://example.com/users/1');
}, 200)
Enter fullscreen mode Exit fullscreen mode

Retry in the Http client

$response = Http::retries(3, 200)->get('http://example.com/users/1');
Enter fullscreen mode Exit fullscreen mode

I hope you enjoy the code.

Discussion (0)