Skip to content

Instantly share code, notes, and snippets.

@HonzaMac
Created November 6, 2015 22:44
Show Gist options
  • Save HonzaMac/4f8c401ddd36fa6b1f12 to your computer and use it in GitHub Desktop.
Save HonzaMac/4f8c401ddd36fa6b1f12 to your computer and use it in GitHub Desktop.
Retry any function in php
<?php
if (!function_exists('retry')) {
/**
* Retries callable
*
* Could be specified how many times, default is 1 times.
*
* @param callable $what
* @param int $retry how many time should it be retried, default is 1
* @return mixed
* @throws Exception
*/
function retry(callable $what, $retry = 1)
{
again:
try {
return $what();
} catch (\RetryableException $e) {
if ($retry-- > 0) {
goto again;
}
throw $e;
}
}
/**
* Class RetryableException
* To be able to specify specific conditions for repeating
*/
class RetryableException extends \Exception{}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment