phpgt/async

基于Promise的非阻塞操作。

资助包维护!
phpgt

v1.0.0 2023-01-19 11:11 UTC

README

要在PHP中运行异步代码,需要一个在后台运行的循环来观察和派发事件,并处理Promise的解析。

此存储库提供了Loop的概念、不同的Timer实现以及Event对象的发布-订阅模型。

PHP.Gt/Async build status PHP.Gt/Async code quality PHP.Gt/Async code coverage PHP.Gt/Async latest release PHP.Gt/Async documentation

示例用法

一个包含三个单独定时器的循环,分别在1秒、5秒和10秒。

$timeAtScriptStart = microtime(true);

$timer = new IndividualTimer();
$timer->addTriggerTime($timeAtScriptStart + 1);
$timer->addTriggerTime($timeAtScriptStart + 5);
$timer->addTriggerTime($timeAtScriptStart + 10);

$timer->addCallback(function() use($timeAtScriptStart) {
	$now = microtime(true);
	$secondsPassed = round($now - $timeAtScriptStart);
	echo "Number of seconds passed: $secondsPassed", PHP_EOL;
});

$loop = new Loop();
$loop->addTimer($timer);
echo "Starting...", PHP_EOL;
$loop->run();