-
-
Save urameshibr/7e1e357e9a1346f70a8326629f9c5eda to your computer and use it in GitHub Desktop.
A retry function for PHP.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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 | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment