-
-
Notifications
You must be signed in to change notification settings - Fork 1
Getting started
In this guide we will install the package, create a loop, add timers, and stop the loop cleanly.
composer require phpgt/asyncphpgt/promise is installed as a dependency, so the loop is ready for the deferred work covered later in this guide.
use GT\Async\Loop;
$loop = new Loop();Nothing happens yet because the loop has no timers to observe.
IndividualTimer schedules one or more exact trigger times.
use GT\Async\Timer\IndividualTimer;
$timer = new IndividualTimer(1.5);
$timer->addCallback(function() {
echo "First callback", PHP_EOL;
});
$loop->addTimer($timer);Passing 1.5 to the constructor means "run once, one and a half seconds from now".
PeriodicTimer schedules callbacks every fixed number of seconds.
use Gt\Async\Timer\PeriodicTimer;
$count = 0;
$periodicTimer = new PeriodicTimer(0.5, true);
$periodicTimer->addCallback(function() use(&$count, $loop) {
$count++;
echo "Tick $count", PHP_EOL;
if($count === 3) {
$loop->halt();
}
});
$loop->addTimer($periodicTimer);The second constructor argument controls the first tick:
-
truemeans the first tick is immediate -
falsemeans the first tick happens after the first period has passed
$loop->run();The loop will keep going until one of these things happens:
- there are no more scheduled timers
- one of the callbacks calls
$loop->halt() - deferred completion tracking halts the loop, which we will cover later
If we call run(false), the loop performs one pass over the timers that are currently due and then returns.
$loop->run(false);This is useful when another part of the application controls the outer execution flow.
Next, continue with Timers to see how the two timer types behave in more detail.