EasySwoole 异步任务Task 采用独立组件实现,需要独立安装 task组件。
安装 :
composer require easyswoole/task --ignore-platform-reqs
在 easyswoole 配置
return [
'MAIN_SERVER' => [
'TASK'=>[
'workerNum'=>4,
'maxRunningNum'=>128,
'timeout'=>15
],
],
];
使用方法- 闭包使用:
在控制器使用
<?php
use EasySwoole\EasySwoole\Task\TaskManager;
class Index extends BaseController
{
function index()
{
$task = TaskManager::getInstance();
$task->async(function (){
echo "异步调用task1\n";
});
$data = $task->sync(function (){
echo "同步调用task1\n";
return "可以返回调用结果\n";
});
$this->response()->write($data);
}
}
使用方法 - 任务模板
<?php
namespace App\Task;
use EasySwoole\Task\AbstractInterface\TaskInterface;
use Swoole\Coroutine;
class TestTask implements TaskInterface
{
protected $data;
//通过构造函数,传入数据,获取该次任务的数据
public function __construct($data)
{
$this->data = $data;
}
function run(int $taskId, int $workerIndex)
{
Coroutine::sleep(10);
$cid = \Co::getCid();
var_dump("模板任务运行 {$cid}");
//只有同步调用才能返回数据
return "返回值:".$this->data['name'];
// TODO: Implement run() method.
}
function onException(\Throwable $throwable, int $taskId, int $workerIndex)
{
// TODO: Implement onException() method.
}
}
调用
<?php
/**
* Created by PhpStorm.
* User: Tioncico
* Date: 2019/11/20 0020
* Time: 10:14
*/
namespace App\HttpController;
use App\Task\TestTask;
use EasySwoole\EasySwoole\Task\TaskManager;
class Index extends BaseController
{
function index()
{
$task = TaskManager::getInstance();
$task->async(new TestTask(['name'=>xxx']));
$data = $task->sync(new TestTask(['name'=>'xxx']));
$this->response()->write($data);
}
}
网友评论