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/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; } } 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); + } }