Skip to content

Commit ff10787

Browse files
author
Greg Bowler
committed
Add IndividualTimer example
1 parent a4ec8c5 commit ff10787

2 files changed

Lines changed: 32 additions & 2 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
/**
3+
* This example shows how an IndividualTimer can be used to schedule some ticks
4+
* in the future. Here, the callback function simply calculates how many seconds
5+
* have passed since the script's start and echos. You can see the correlation
6+
* with the output to the three trigger times that are added after creating
7+
* the IndividualTimer object.
8+
*/
9+
require("../vendor/autoload.php");
10+
11+
$timeAtScriptStart = microtime(true);
12+
13+
$timer = new \Gt\Async\Timer\IndividualTimer();
14+
$timer->addTriggerTime($timeAtScriptStart + 1);
15+
$timer->addTriggerTime($timeAtScriptStart + 5);
16+
$timer->addTriggerTime($timeAtScriptStart + 10);
17+
18+
$timer->addCallback(function() use($timeAtScriptStart) {
19+
$now = microtime(true);
20+
$secondsPassed = round($now - $timeAtScriptStart);
21+
echo "Number of seconds passed: $secondsPassed", PHP_EOL;
22+
});
23+
24+
$loop = new \Gt\Async\Loop();
25+
$loop->addTimer($timer);
26+
echo "Starting...", PHP_EOL;
27+
$loop->run();

src/Timer/IndividualTimer.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22
namespace Gt\Async\Timer;
33

44
class IndividualTimer extends Timer {
5-
public function __construct(float $triggerTime) {
5+
public function __construct(float $triggerTime = null) {
66
parent::__construct();
7-
$this->addTriggerTime($triggerTime);
7+
8+
if(!is_null($triggerTime)) {
9+
$this->addTriggerTime($triggerTime);
10+
}
811
}
912

1013
public function addTriggerTime(float $triggerTime):void {

0 commit comments

Comments
 (0)