14. Task机制-四、使用

时间:2024-10-25 12:47:51

1. 使用注解

<?php
namespace App\Service;

use Hyperf\Coroutine\Coroutine;
use Hyperf\Task\Annotation\Task;

class TaskService
{
    #[Task]
    public function handle($cid)
    {
        return [
            'worker.cid' => $cid,
            // task_enable_coroutine 为 false 时返回 -1,反之 返回对应的协程 ID
            'task.cid' => Coroutine::id(),
        ];
    }
}
  • 调用
<?php
namespace App\Controller;

use App\Service\TaskService;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;

#[AutoController]
class TaskController
{
    #[Inject]
    private TaskService $taskService;

    public function index(RequestInterface $request, ResponseInterface $response)
    {
        $result = $this->taskService->handle(Coroutine::id());

        return $response->json($result);
    }
}

2. 主动方法投递(不推荐)

<?php

use Hyperf\Coroutine\Coroutine;
use Hyperf\Context\ApplicationContext;
use Hyperf\Task\TaskExecutor;
use Hyperf\Task\Task;

class MethodTask
{
    public function handle($cid)
    {
        return [
            'worker.cid' => $cid,
            // task_enable_coroutine 为 false 时返回 -1,反之 返回对应的协程 ID
            'task.cid' => Coroutine::id(),
        ];
    }
}

// 使用
$container = ApplicationContext::getContainer();
$exec = $container->get(TaskExecutor::class);
$result = $exec->execute(new Task([MethodTask::class, 'handle'], [Coroutine::id()]));