diff --git a/src/Interval.php b/src/Interval.php new file mode 100644 index 00000000..7618a31a --- /dev/null +++ b/src/Interval.php @@ -0,0 +1,98 @@ +callbackId = EventLoop::repeat($interval, $closure); + + if (!$reference) { + EventLoop::unreference($this->callbackId); + } + } + + public function __destruct() + { + EventLoop::cancel($this->callbackId); + } + + /** + * @return bool True if the internal watcher is referenced. + */ + public function isReferenced(): bool + { + return EventLoop::isReferenced($this->callbackId); + } + + /** + * 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->callbackId); + + 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->callbackId); + + return $this; + } + + /** + * @return bool True if the repeating timer is enabled. + */ + public function isEnabled(): bool + { + return EventLoop::isEnabled($this->callbackId); + } + + /** + * Restart the repeating timer if previously stopped with {@see self::disable()}. + * + * @return $this + */ + public function enable(): self + { + EventLoop::enable($this->callbackId); + + return $this; + } + + /** + * Stop the repeating timer. Restart it with {@see self::enable()}. + * + * @return $this + */ + public function disable(): self + { + EventLoop::disable($this->callbackId); + + return $this; + } +} diff --git a/test/IntervalTest.php b/test/IntervalTest.php new file mode 100644 index 00000000..1f163a30 --- /dev/null +++ b/test/IntervalTest.php @@ -0,0 +1,49 @@ +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); + } +}