Skip to content

Commit 1567309

Browse files
authored
Merge pull request #16 from chrisharrison/feature/periodic-tasks
Add the ability to run periodic tasks
2 parents 0d8ba1d + 58969ac commit 1567309

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-0
lines changed

src/Server.php

Lines changed: 13 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
/**
@@ -90,6 +96,8 @@ protected function createConnection($resource): Connection
9096
public function run(): void
9197
{
9298
while (true) {
99+
$this->timers->runAll();
100+
93101
$changed_sockets = $this->allsockets;
94102
@stream_select($changed_sockets, $write, $except, 0, 5000);
95103
foreach ($changed_sockets as $socket) {
@@ -490,4 +498,9 @@ public function getMaxClients(): int
490498
{
491499
return $this->maxClients;
492500
}
501+
502+
public function addTimer(int $interval, callable $task): void
503+
{
504+
$this->timers->addTimer(new Timer($interval, $task));
505+
}
493506
}

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)