TimedJob.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCP\BackgroundJob;
  8. use OCP\ILogger;
  9. /**
  10. * Simple base class to extend to run periodic background jobs.
  11. * Call setInterval with your desired interval in seconds from the constructor.
  12. *
  13. * @since 15.0.0
  14. */
  15. abstract class TimedJob extends Job {
  16. protected int $interval = 0;
  17. protected int $timeSensitivity = IJob::TIME_SENSITIVE;
  18. /**
  19. * Set the interval for the job
  20. *
  21. * @param int $seconds the time to pass between two runs of the same job in seconds
  22. *
  23. * @since 15.0.0
  24. */
  25. public function setInterval(int $seconds) {
  26. $this->interval = $seconds;
  27. }
  28. /**
  29. * Whether the background job is time sensitive and needs to run soon after
  30. * the scheduled interval, of if it is okay to be delayed until a later time.
  31. *
  32. * @return bool
  33. * @since 24.0.0
  34. */
  35. public function isTimeSensitive(): bool {
  36. return $this->timeSensitivity === IJob::TIME_SENSITIVE;
  37. }
  38. /**
  39. * If your background job is not time sensitive (sending instant email
  40. * notifications, etc.) it would be nice to set it to IJob::TIME_INSENSITIVE
  41. * This way the execution can be delayed during high usage times.
  42. *
  43. * @param int $sensitivity
  44. * @psalm-param IJob::TIME_* $sensitivity
  45. * @return void
  46. * @since 24.0.0
  47. */
  48. public function setTimeSensitivity(int $sensitivity): void {
  49. if ($sensitivity !== IJob::TIME_SENSITIVE &&
  50. $sensitivity !== IJob::TIME_INSENSITIVE) {
  51. throw new \InvalidArgumentException('Invalid sensitivity');
  52. }
  53. $this->timeSensitivity = $sensitivity;
  54. }
  55. /**
  56. * Run the job if the last run is more than the interval ago
  57. *
  58. * @param IJobList $jobList
  59. * @param ILogger|null $logger
  60. *
  61. * @since 15.0.0
  62. * @deprecated since 25.0.0 Use start() instead
  63. */
  64. final public function execute(IJobList $jobList, ?ILogger $logger = null) {
  65. $this->start($jobList);
  66. }
  67. /**
  68. * Run the job if the last run is more than the interval ago
  69. *
  70. * @since 25.0.0
  71. */
  72. final public function start(IJobList $jobList): void {
  73. if (($this->time->getTime() - $this->lastRun) > $this->interval) {
  74. parent::start($jobList);
  75. }
  76. }
  77. }