Skip to content

Instantly share code, notes, and snippets.

@mudge
Created July 8, 2013 13:27
Show Gist options
  • Save mudge/5948769 to your computer and use it in GitHub Desktop.
Save mudge/5948769 to your computer and use it in GitHub Desktop.
A retry function for PHP.
<?php
require_once dirname(__FILE__) . '/../lib/simpletest/autorun.php';
function retry($f, $delay = 10, $retries = 3)
{
try {
return $f();
} catch (Exception $e) {
if ($retries > 0) {
sleep($delay);
return retry($f, $delay, $retries - 1);
} else {
throw $e;
}
}
}
class RetryTest extends UnitTestCase
{
function testRetryWithNoExceptions()
{
$name = "Bob";
$result = retry(
function () use ($name) {
return $name . "!";
},
0.1
);
$this->assertEqual("Bob!", $result);
}
function testRetryWithException()
{
$fail = true;
$result = retry(
function () use (&$fail) {
if ($fail) {
$fail = false;
throw new Exception("Boom!");
} else {
return "Woo!";
}
},
0.1
);
$this->assertEqual("Woo!", $result);
}
function testRetryTriesTheExpectedNumberOfTimes()
{
$count = 0;
try {
retry(
function () use (&$count) {
$count += 1;
throw new Exception("Boom!");
},
0.1
);
} catch (Exception $e) {
}
$this->assertEqual(4, $count);
}
function testRetryWithConstantFailure()
{
$this->expectException(new PatternExpectation("/I will never work./"));
$result = retry(
function () {
throw new Exception("I will never work.");
},
0.1
);
}
}
@vlakoff
Copy link

vlakoff commented Jun 16, 2019

FYI, Laravel has a retry() helper for this. (code)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment