Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
);

?>
```

Expand Down
3 changes: 2 additions & 1 deletion src/retry.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

class FailingTooHardException extends \Exception {}

function retry($retries, callable $fn)
function retry($retries, callable $fn, $delay = 0)
{
beginning:
try {
Expand All @@ -14,6 +14,7 @@ function retry($retries, callable $fn)
throw new FailingTooHardException('', 0, $e);
}
$retries--;
sleep($delay);
goto beginning;
}
}
20 changes: 20 additions & 0 deletions tests/RetryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}