Skip to content

Commit 99384cf

Browse files
committed
Add the ability to run periodic tasks
1 parent 002c173 commit 99384cf

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed

src/Server.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,11 @@ class Server extends Socket
6060
*/
6161
private $maxRequestsPerMinute = 50;
6262

63+
/**
64+
* @var TimerCollection $timers
65+
*/
66+
private $timers;
67+
6368
/**
6469
* @param string $host
6570
* @param int $port
@@ -68,6 +73,7 @@ public function __construct($host = 'localhost', $port = 8000)
6873
{
6974
parent::__construct($host, $port);
7075
$this->log('Server created');
76+
$this->timers = new TimerCollection();
7177
}
7278

7379
/**
@@ -92,6 +98,7 @@ public function run(): void
9298
while (true) {
9399
$changed_sockets = $this->allsockets;
94100
@stream_select($changed_sockets, $write = null, $except = null, 0, 5000);
101+
$this->timers->runAll();
95102
foreach ($changed_sockets as $socket) {
96103
if ($socket == $this->master) {
97104
if (($ressource = stream_socket_accept($this->master)) === false) {
@@ -490,4 +497,9 @@ public function getMaxClients(): int
490497
{
491498
return $this->maxClients;
492499
}
500+
501+
public function addTimer(int $interval, callable $task): void
502+
{
503+
$this->timers->addTimer(new Timer($interval, $task));
504+
}
493505
}

src/Timer.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Bloatless\WebSocket;
6+
7+
final class Timer
8+
{
9+
private $interval;
10+
private $task;
11+
private $lastRun;
12+
13+
public function __construct(int $interval, callable $task)
14+
{
15+
$this->interval = $interval;
16+
$this->task = $task;
17+
$this->lastRun = 0;
18+
}
19+
20+
public function run(): void
21+
{
22+
$now = round(microtime(true) * 1000);
23+
if ($now - $this->lastRun < $this->interval) {
24+
return;
25+
}
26+
27+
$this->lastRun = $now;
28+
29+
$task = $this->task;
30+
$task();
31+
}
32+
}

src/TimerCollection.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Bloatless\WebSocket;
6+
7+
final class TimerCollection
8+
{
9+
/**
10+
* @var Timer[]
11+
*/
12+
private $timers;
13+
14+
public function __construct(array $timers = [])
15+
{
16+
$this->timers = $timers;
17+
}
18+
19+
public function addTimer(Timer $timer)
20+
{
21+
$this->timers[] = $timer;
22+
}
23+
24+
public function runAll(): void
25+
{
26+
foreach ($this->timers as $timer) {
27+
$timer->run();
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)