There are certain operations that can have a high probability of failure. For instance, sending a request to a third-party API. You’re not sure whether it will work every time flawlessly because it’s not in your control. If the API endpoint you’re hitting is not responding, you might end up with an exception straight away.
I’m sure we all don’t want that to happen. So, what would you do in such a scenario? You’ll “retry” the same operation, no?
Well, if your application is built on top of Laravel, there’s a really handy helper function that exists in the framework which can help you do just that.
The retry helper function
Essentially, retry is a general-purpose helper function that helps you attempt the given callback until the given maximum attempt threshold is met.
Here’s the signature of this function.
function retry($times, callable $callback, $sleep = 0, $when = null);
As you can see, the function accepts four arguments.
$times - The maximum number of times you want to attempts the callback.
$callback - The callback that you want to get retried (on an exception).
$sleep (optional) - The number of milliseconds that Laravel should wait in between attempts.
$when (optional) - The callback where you can specify an alternative logic (a predicate) on which you want the original callback to be attempted.
So, if you want to perform an API call that you want to be retried (on failure) 3 times every 200 milliseconds, you can use the retry function like so.