Laravel 5: Attempt an Error-Prone Operation a Number of Times With retry

April 14, 2018 —John Koster

The retry helper function can be used to attempt an operation that is prone to throwing exceptions a set number of times. This helper function can also wait a certain number of milliseconds between attempts.

If the operation specified in the $callback has not succeeded by the last attempt, the inner exception will be thrown.

#Signature

The signature of the retry function is:

1function retry(
2 $times,
3 callable $callback,
4 $sleep = 0
5);

#Example Use

In the following example, we will purposely throw an exception on each iteration of the retry function. The exception will only be thrown on the final retry attempt:

1$value = retry(3, function () {
2 throw new Exception('This will always fail');
3}, 10);

We can pass in an outside variable to the retry callback to investigate the behavior of the retry function further. In the following example, we keep track of which iteration the retry function is on and prevent it from throwing the exception on the final attempt:

It is important that to note that the following code example is just used to help analyze the retry function's behavior; utilizing code like this in an actual application is not recommended.

1$numberOfTimesAttempted = 0;
2 
3$value = retry(3, function () use (
4 &$numberOfTimesAttempted
5 ) {
6 $numberOfTimesAttempted += 1;
7 
8 if ($numberOfTimesAttempted > 2) {
9 return;
10 }
11 
12 throw new Exception('This will fail');
13}, 10);

Unlike the first example, the previous example will not throw any exception since the callback returns on the last attempt before the exception can be thrown.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.