Getting started
In this guide we will install the package, create a loop, add timers, and stop the loop cleanly.
1. Install the package
composer require phpgt/async
phpgt/promise is installed as a dependency, so the loop is ready for the deferred work covered later in this guide.
2. Create a loop
use GT\Async\Loop;
$loop = new Loop();
Nothing happens yet because the loop has no timers to observe.
3. Add a one-off timer
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”.
4. Add a repeating timer
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 immediatefalsemeans the first tick happens after the first period has passed
5. Run the loop
$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
6. Run only one pass
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.