From c296aa8860033b3f235b311ba2e1d9ae9c00a062 Mon Sep 17 00:00:00 2001 From: Aaron Piotrowski Date: Wed, 17 Jul 2024 23:02:25 -0500 Subject: [PATCH] Add Interval --- src/Interval.php | 98 +++++++++++++++++++++++++++++++++++++++++++ test/IntervalTest.php | 48 +++++++++++++++++++++ 2 files changed, 146 insertions(+) create mode 100644 src/Interval.php create mode 100644 test/IntervalTest.php diff --git a/src/Interval.php b/src/Interval.php new file mode 100644 index 00000000..9877598c --- /dev/null +++ b/src/Interval.php @@ -0,0 +1,98 @@ +watcher = EventLoop::repeat($interval, $closure); + + if (!$reference) { + EventLoop::unreference($this->watcher); + } + } + + public function __destruct() + { + EventLoop::cancel($this->watcher); + } + + /** + * @return bool True if the internal watcher is referenced. + */ + public function isReferenced(): bool + { + return EventLoop::isReferenced($this->watcher); + } + + /** + * References the internal watcher in the event loop, keeping the loop running while the repeat loop is enabled. + * + * @return $this + */ + public function reference(): self + { + EventLoop::reference($this->watcher); + + return $this; + } + + /** + * Unreferences the internal watcher in the event loop, allowing the loop to stop while the repeat loop is enabled. + * + * @return $this + */ + public function unreference(): self + { + EventLoop::unreference($this->watcher); + + return $this; + } + + /** + * @return bool True if the repeating timer is enabled. + */ + public function isEnabled(): bool + { + return EventLoop::isEnabled($this->watcher); + } + + /** + * Restart the repeating timer if previously stopped with {@see self::disable()}. + * + * @return $this + */ + public function enable(): self + { + EventLoop::enable($this->watcher); + + return $this; + } + + /** + * Stop the repeating timer. Restart it with {@see self::enable()}. + * + * @return $this + */ + public function disable(): self + { + EventLoop::disable($this->watcher); + + return $this; + } +} diff --git a/test/IntervalTest.php b/test/IntervalTest.php new file mode 100644 index 00000000..0950dcb1 --- /dev/null +++ b/test/IntervalTest.php @@ -0,0 +1,48 @@ +disable(); + self::assertFalse($interval->isEnabled()); + + delay($timeout * 2); + + self::assertSame(0, $invocationCount); + + $interval->enable(); + self::assertTrue($interval->isEnabled()); + + delay($timeout * 1.5); + + self::assertSame(1, $invocationCount); + } +}