Skip to content

Commit

Permalink
Add some style fixes to timer methods
Browse files Browse the repository at this point in the history
  • Loading branch information
nekudo committed Nov 15, 2020
1 parent 1567309 commit bed1714
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 4 deletions.
2 changes: 2 additions & 0 deletions cli/server.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
require __DIR__ . '/../src/Connection.php';
require __DIR__ . '/../src/Socket.php';
require __DIR__ . '/../src/Server.php';
require __DIR__ . '/../src/Timer.php';
require __DIR__ . '/../src/TimerCollection.php';

require __DIR__ . '/../src/Application/ApplicationInterface.php';
require __DIR__ . '/../src/Application/Application.php';
Expand Down
6 changes: 6 additions & 0 deletions src/Server.php
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,12 @@ public function getMaxClients(): int
return $this->maxClients;
}

/**
* Adds a periodic timer.
*
* @param int $interval Interval in microseconds.
* @param callable $task
*/
public function addTimer(int $interval, callable $task): void
{
$this->timers->addTimer(new Timer($interval, $task));
Expand Down
20 changes: 17 additions & 3 deletions src/Timer.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,19 @@

final class Timer
{
/**
* @var int $interval
*/
private $interval;

/**
* @var callable $task
*/
private $task;

/**
* @var int $lastRun
*/
private $lastRun;

public function __construct(int $interval, callable $task)
Expand All @@ -17,6 +28,11 @@ public function __construct(int $interval, callable $task)
$this->lastRun = 0;
}

/**
* Executes the timer if intervall has passed.
*
* @return void
*/
public function run(): void
{
$now = round(microtime(true) * 1000);
Expand All @@ -25,8 +41,6 @@ public function run(): void
}

$this->lastRun = $now;

$task = $this->task;
$task();
call_user_func($this->task);
}
}
10 changes: 9 additions & 1 deletion src/TimerCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
final class TimerCollection
{
/**
* @var Timer[]
* @var array $timers
*/
private $timers;

Expand All @@ -16,11 +16,19 @@ public function __construct(array $timers = [])
$this->timers = $timers;
}

/**
* Adds a timer.
*
* @param Timer $timer
*/
public function addTimer(Timer $timer)
{
$this->timers[] = $timer;
}

/**
* Executes/runs all timers.
*/
public function runAll(): void
{
foreach ($this->timers as $timer) {
Expand Down

0 comments on commit bed1714

Please sign in to comment.