From 487605b4f4038d32f89efb95837b7f0947fa17ac Mon Sep 17 00:00:00 2001 From: Kevin Boyd Date: Fri, 19 Sep 2014 15:40:25 -0700 Subject: [PATCH 1/2] Add an optional retry delay By specifying an optional 3rd parameter (in seconds), you can cause a small delay between retries. This can be useful to avoid the perception of flooding. --- src/retry.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/retry.php b/src/retry.php index 17fc7dd..8ecbaf3 100644 --- a/src/retry.php +++ b/src/retry.php @@ -4,7 +4,7 @@ class FailingTooHardException extends \Exception {} -function retry($retries, callable $fn) +function retry($retries, callable $fn, $delay = 0) { beginning: try { @@ -14,6 +14,7 @@ function retry($retries, callable $fn) throw new FailingTooHardException('', 0, $e); } $retries--; + sleep($delay); goto beginning; } } From 2cd43bcdfeebb9aa5bc4081d15772e5ce845b49e Mon Sep 17 00:00:00 2001 From: Kevin Boyd Date: Fri, 19 Sep 2014 15:59:35 -0700 Subject: [PATCH 2/2] Updating README with an example, adding a unit test --- README.md | 10 ++++++++++ tests/RetryTest.php | 20 ++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/README.md b/README.md index 9b334a6..30e710c 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,16 @@ $user = retry(5, () ==> User::find($id)); $user = retry(INF, () ==> { throw new RuntimeException('never gonna give you up'); }); + +// set an optional retry delay to prevent floods +$user = retry( + 5, + function () use ($id) { + return User::find($id); + }, + 5 // retry delay (in seconds) +); + ?> ``` diff --git a/tests/RetryTest.php b/tests/RetryTest.php index ba62c4a..072f159 100644 --- a/tests/RetryTest.php +++ b/tests/RetryTest.php @@ -66,4 +66,24 @@ function testRetryManyTimes() $this->assertSame('dogecoin', $e->getPrevious()->getMessage()); $this->assertSame(1001, $i); } + + function testRetryDelay() + { + $e = null; + $i = 0; + $t = microtime(true); + try { + retry(1, function () use (&$i, &$failed) { + $i++; + throw new \RuntimeException('dogecoin'); + }, 1); + } catch (\Exception $e) { + } + + $this->assertInstanceof('igorw\FailingTooHardException', $e); + $this->assertInstanceof('RuntimeException', $e->getPrevious()); + $this->assertSame('dogecoin', $e->getPrevious()->getMessage()); + $this->assertSame(2, $i); + $this->assertGreaterThan(1, microtime(true) - $t); + } }