diff --git a/src/Server.php b/src/Server.php index 12ff034..4367635 100644 --- a/src/Server.php +++ b/src/Server.php @@ -60,6 +60,11 @@ class Server extends Socket */ private $maxRequestsPerMinute = 50; + /** + * @var TimerCollection $timers + */ + private $timers; + /** * @param string $host * @param int $port @@ -68,6 +73,7 @@ public function __construct($host = 'localhost', $port = 8000) { parent::__construct($host, $port); $this->log('Server created'); + $this->timers = new TimerCollection(); } /** @@ -90,6 +96,8 @@ protected function createConnection($resource): Connection public function run(): void { while (true) { + $this->timers->runAll(); + $changed_sockets = $this->allsockets; @stream_select($changed_sockets, $write, $except, 0, 5000); foreach ($changed_sockets as $socket) { @@ -490,4 +498,9 @@ public function getMaxClients(): int { return $this->maxClients; } + + public function addTimer(int $interval, callable $task): void + { + $this->timers->addTimer(new Timer($interval, $task)); + } } diff --git a/src/Timer.php b/src/Timer.php new file mode 100644 index 0000000..861929f --- /dev/null +++ b/src/Timer.php @@ -0,0 +1,32 @@ +interval = $interval; + $this->task = $task; + $this->lastRun = 0; + } + + public function run(): void + { + $now = round(microtime(true) * 1000); + if ($now - $this->lastRun < $this->interval) { + return; + } + + $this->lastRun = $now; + + $task = $this->task; + $task(); + } +} diff --git a/src/TimerCollection.php b/src/TimerCollection.php new file mode 100644 index 0000000..907011f --- /dev/null +++ b/src/TimerCollection.php @@ -0,0 +1,30 @@ +timers = $timers; + } + + public function addTimer(Timer $timer) + { + $this->timers[] = $timer; + } + + public function runAll(): void + { + foreach ($this->timers as $timer) { + $timer->run(); + } + } +}