Skip to content

Instantly share code, notes, and snippets.

@wryk
Created September 17, 2020 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wryk/65a2ccf298ec282209e30d55126aece5 to your computer and use it in GitHub Desktop.
Save wryk/65a2ccf298ec282209e30d55126aece5 to your computer and use it in GitHub Desktop.
<?php
// util
$constant = function ($value) {
return function ($_) use ($value) {
return $value;
};
};
$lessThan = function ($right) {
return function ($left) use ($right) {
return $left < $right;
};
};
$linear = function ($ms) {
return function ($n) use ($ms) {
return $n * $ms;
};
};
$exponential = function ($ms) {
return function ($n) use ($ms) {
return pow(2, $n - 1) * $ms;
};
};
// implementation
$retry = function ($allowAttempt, $backoff, $supportsException, $fn) {
$attempt = 0;
while (true) {
if ($attempt > 0) {
usleep($backoff($attempt) * 1000);
}
try {
return $fn();
} catch (\Exception $exception) {
if (!$supportsException($exception)) {
throw $exception;
}
if (!$allowAttempt(++$attempt)) {
throw new \Exception('Max attempts');
}
}
}
};
// test
$result = $retry(
$lessThan(5),
$linear(2000),
$constant(true),
function () {
if (rand(0, 2)) {
var_dump('has exception');
throw new \Exception('random error');
} else {
var_dump('has result');
return 'hello world';
}
}
);
var_dump($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment