Skip to content

Commit 7a12616

Browse files
committed
fix(task): 使用 swoole 投递异步 Task
``` // 实例化TestTask并通过deliver投递,此操作是异步的,投递后立即返回,由Task进程继续处理TestTask中的handle逻辑 use Hhxsv5\LaravelS\Swoole\Task\Task; $task = new TestTask('task data'); // $task->delay(3);// 延迟3秒投放任务 $ret = Task::deliver($task); var_dump($ret);//判断是否投递成功 ```
1 parent 0a39022 commit 7a12616

File tree

3 files changed

+39
-29
lines changed

3 files changed

+39
-29
lines changed

laravel/app/Listeners/TestListener.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
namespace App\Listeners;
1111

12-
use App\Tasks\TaskEvent;
12+
use App\Tasks\TestTask;
1313
use Hhxsv5\LaravelS\Swoole\Task\Task;
1414
use Hhxsv5\LaravelS\Swoole\Task\Event;
1515
use Hhxsv5\LaravelS\Swoole\Task\Listener;

laravel/app/Tasks/TaskEvent.php

Lines changed: 0 additions & 28 deletions
This file was deleted.

laravel/app/Tasks/TestTask.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
/**
3+
* 创建异步任务类
4+
* User: lisgroup
5+
* Date: 19-4-13
6+
* Time: 下午10:23
7+
*/
8+
9+
namespace App\Tasks;
10+
11+
use Hhxsv5\LaravelS\Swoole\Task\Task;
12+
13+
class TestTask extends Task
14+
{
15+
private $data;
16+
private $result;
17+
18+
public function __construct($data)
19+
{
20+
$this->data = $data;
21+
}
22+
23+
// 处理任务的逻辑,运行在Task进程中,不能投递任务
24+
public function handle()
25+
{
26+
\Log::info(__CLASS__.':handle start', [$this->data]);
27+
sleep(2);// 模拟一些慢速的事件处理
28+
// throw new \Exception('an exception');// handle时抛出的异常上层会忽略,并记录到Swoole日志,需要开发者try/catch捕获处理
29+
$this->result = 'the result of '.$this->data;
30+
}
31+
32+
// 可选的,完成事件,任务处理完后的逻辑,运行在Worker进程中,可以投递任务
33+
public function finish()
34+
{
35+
\Log::info(__CLASS__.':finish start', [$this->result]);
36+
// Task::deliver(new TestTask2('task2')); // 投递其他任务
37+
}
38+
}

0 commit comments

Comments
 (0)