Skip to content

Instantly share code, notes, and snippets.

@mylk
Last active October 15, 2016 14:10
Show Gist options
  • Save mylk/4eb470ba26c1206234b346812baee5b3 to your computer and use it in GitHub Desktop.
Save mylk/4eb470ba26c1206234b346812baee5b3 to your computer and use it in GitHub Desktop.
A method that performs exponential backoff on a callback method
<?php
// $this->executeWithExponentialBackOff("self::myMethodName", array("id" => 1), 64);
// in this exmaple myFunctionName() is private and resides in the same class as executeWithExponentialBackOff().
// myFunctionName() has to throw an exception when it fails for the backoff to be performed.
class Foo
{
private function executeWithExponentialBackOff($callback, $parameters, $timeout)
{
$results = null;
$success = true;
$backoffSeconds = 1;
do {
if (!$success) {
\printf("Backing-off for %s and retrying...%s", $backoffSeconds, PHP_EOL);
\sleep($backoffSeconds);
}
try {
$results = \call_user_func_array($callback, $parameters);
$success = true;
$backoffSeconds = 1;
} catch (\Exception $ex) {
$success = false;
$errorMessage = \sprintf("Function failed with error: \"%s\".", $ex->getMessage());
$backoffSeconds = $backoffSeconds << 1;
if ($backoffSeconds >= $timeout) {
\printf("Quitting, backoff timeout reached :-(%s", PHP_EOL);
break;
}
\printf("%s%s", $errorMessage, PHP_EOL);
}
} while (!$success);
return $results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment