1. <?php
  2. /**
  3. * Wraps task execution to handle errors and retry with fixed intervals.
  4. *
  5. * @param callable $task The task to execute.
  6. * @param int $maxRetries The maximum number of retry attempts.
  7. * @param int $retryInterval The interval between retry attempts in seconds.
  8. * @return bool True on success, false on failure after maxRetries.
  9. * @throws Exception If the task throws an exception and maxRetries is reached.
  10. */
  11. function wrapTask(callable $task, int $maxRetries = 3, int $retryInterval = 5): bool
  12. {
  13. $retries = 0;
  14. do {
  15. try {
  16. return $task(); // Execute the task
  17. } catch (\Exception $e) {
  18. $retries++;
  19. if ($retries > $maxRetries) {
  20. throw $e; // Re-throw the exception if max retries reached
  21. }
  22. sleep($retryInterval); // Wait before retrying
  23. }
  24. } while (true); // Infinite loop until task succeeds or max retries are reached.
  25. }

Add your comment