Skip to content

Instantly share code, notes, and snippets.

@bosunolanrewaju
Forked from mudge/test.retry.php
Last active May 9, 2022 17:21
Show Gist options
  • Save bosunolanrewaju/5d43595f7a785bc3b31d2b7e6da7977e to your computer and use it in GitHub Desktop.
Save bosunolanrewaju/5d43595f7a785bc3b31d2b7e6da7977e to your computer and use it in GitHub Desktop.
A retry function for PHP.
<?php
require_once dirname(__FILE__) . '/../lib/simpletest/autorun.php';
// Retries $f (A function) with arguments ($args as array)
// 3 ($retries) times after 10 secs $delay
// Usage:
// retry( 'function_name', array('arg1', 'arg2'), 15, 5 );
// #=> Retries function_name 5 times with arg1 and $arg2 as arguments at interval of 15 secs
function retry($f, $args = null, $delay = 10, $retries = 3)
{
try {
if ( is_null( $args ) )
return $f();
if ( is_array( $args ) )
return call_user_func_array( $f, $args )
return call_user_func_array( $f, array( $args ) );
} 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
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment