kesha-dev / yii2-async
为 Yii2 应用程序提供一种简单的方式来异步运行代码
v1.0.1
2023-09-06 13:27 UTC
Requires
- php: >7.1
- spatie/async: 1.6.0
Requires (Dev)
- symfony/stopwatch: ^4.0
This package is not auto-updated.
Last update: 2024-09-26 17:46:56 UTC
README
关于它
这是一个扩展,它提供了一个简单的异步运行代码和并行运行代码的方式,基于 spatie/async 对 Yii2 应用的包装。
需求
安装
使用 Composer 安装 Yii2 Async
composer require vxm/yii2-async
使用
配置
将组件添加到您的应用程序配置文件中
[ 'components' => [ 'async' => [ 'class' => 'vxm\async\Async', 'appConfigFile' => '@app/config/async.php' // optional when you need to use yii feature in async process. ] ] ]
由于异步代码在单独的进程中运行,您需要设置 yii 环境来通过属性 appConfigFile
使用组件。异步应用程序配置文件的示例
define('YII_ENV', 'dev'); define('YII_DEBUG', true); return [ 'id' => 'async-app', 'basePath' => __DIR__, 'runtimePath' => __DIR__ . '/runtime', 'aliases' => [ '@frontend' => dirname(__DIR__, 2) . '/frontend', '@backend' => dirname(__DIR__, 2) . '/backend' ] ];
确保在其中定义了所有别名以支持自动加载。
运行异步代码
将其添加到应用程序组件后,现在您可以运行异步代码
Yii::$app->async->run(function() { // do a thing. });
异步事件
在创建异步进程时,您可以在第二个参数中添加以下事件钩子到进程。
Yii::$app->async->run(function() { if (rand(1, 2) === 1) { throw new \YourException; } return 123; }, [ 'success' => function ($result) { echo $result; // 123 }, 'catch' => function (\YourException $exception) { // catch only \YourException }, 'error' => function() { // catch all exceptions }, 'timeout' => function() { // call when task timeout default's 15s } ]);
等待进程
有时您需要等待代码执行,只需在 run()
后调用 wait()
Yii::$app->async->run(function() { // do a thing. })->wait();
或者您也可以等待多个任务执行
Yii::$app->async->run([YourAsyncClass::class, 'handleA']); Yii::$app->async->run([YourAsyncClass::class, 'handleD']); Yii::$app->async->run([YourAsyncClass::class, 'handleC']); Yii::$app->async->run([YourAsyncClass::class, 'handleD']); $results = Yii::$app->async->wait(); // results return from tasks above.
与任务一起工作
除了使用闭包之外,您还可以使用 Task。在需要更多子进程设置工作的情况下,Task 很有用。
Task 类使得这变得更容易。
use vxm\async\Task; class MyTask extends Task { public $productId; public function run() { // Do the real work here. } } // Do task async use like an anonymous above. Yii::$app->async->run(new MyTask([ 'productId' => 123 ]));