InteractsWithTime.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace think\queue;
  3. use Carbon\Carbon;
  4. use DateInterval;
  5. use DateTimeInterface;
  6. trait InteractsWithTime
  7. {
  8. /**
  9. * Get the number of seconds until the given DateTime.
  10. *
  11. * @param DateTimeInterface|DateInterval|int $delay
  12. * @return int
  13. */
  14. protected function secondsUntil($delay)
  15. {
  16. $delay = $this->parseDateInterval($delay);
  17. return $delay instanceof DateTimeInterface
  18. ? max(0, $delay->getTimestamp() - $this->currentTime())
  19. : (int) $delay;
  20. }
  21. /**
  22. * Get the "available at" UNIX timestamp.
  23. *
  24. * @param DateTimeInterface|DateInterval|int $delay
  25. * @return int
  26. */
  27. protected function availableAt($delay = 0)
  28. {
  29. $delay = $this->parseDateInterval($delay);
  30. return $delay instanceof DateTimeInterface
  31. ? $delay->getTimestamp()
  32. : Carbon::now()->addRealSeconds($delay)->getTimestamp();
  33. }
  34. /**
  35. * If the given value is an interval, convert it to a DateTime instance.
  36. *
  37. * @param DateTimeInterface|DateInterval|int $delay
  38. * @return DateTimeInterface|int
  39. */
  40. protected function parseDateInterval($delay)
  41. {
  42. if ($delay instanceof DateInterval) {
  43. $delay = Carbon::now()->add($delay);
  44. }
  45. return $delay;
  46. }
  47. /**
  48. * Get the current system time as a UNIX timestamp.
  49. *
  50. * @return int
  51. */
  52. protected function currentTime()
  53. {
  54. return Carbon::now()->getTimestamp();
  55. }
  56. }