ArrayBackoff.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Support\Backoff;
  12. use Hyperf\Collection\Arr;
  13. use InvalidArgumentException;
  14. class ArrayBackoff
  15. {
  16. private int $lastMillisecond;
  17. /**
  18. * @param array $milliseconds backoff interval
  19. */
  20. public function __construct(private array $milliseconds)
  21. {
  22. if (empty($milliseconds)) {
  23. throw new InvalidArgumentException(
  24. 'The backoff interval milliseconds cannot be empty.'
  25. );
  26. }
  27. $this->lastMillisecond = (int) array_pop($this->milliseconds);
  28. }
  29. /**
  30. * Sleep until the next execution.
  31. */
  32. public function sleep(): void
  33. {
  34. $ms = (int) (array_shift($this->milliseconds) ?? $this->lastMillisecond);
  35. if ($ms === 0) {
  36. return;
  37. }
  38. usleep($ms * 1000);
  39. }
  40. /**
  41. * Get the next backoff for logging, etc.
  42. * @return int next backoff
  43. */
  44. public function nextBackoff(): int
  45. {
  46. return (int) Arr::first($this->milliseconds, default: $this->lastMillisecond);
  47. }
  48. }