Retry Method in Laravel
Let’s learn about Laravel Retry method
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(5, function () {
// Attempt 5 times while resting 100ms between attempts...
}, 100);
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');
You may also retry all of the failed jobs for a particular queue:
php artisan queue:retry --queue=name
To retry all of your failed jobs, execute the queue:retry
command and pass all
as the ID:
php artisan queue:retry al
You can use retry with DB::transaction too.
I hope you found this helpful, any asking let me know!
For more details of OOP: https://github.com/mohasin-dev/Object-Oriented-Programming-in-PHP
Bonus: You must love my most read article : How To Use Single Responsibility Principle in PHP/Laravel
And most GitHub star repo:
https://github.com/mohasinhossain/SOLID-Principles-in-PHP