Asynchronous task

Asynchronous tasks are generally used for scenarios that do not require results and are executed asynchronously, without affecting the main process. The following asynchronous task delivery:

 use Swoft\Task\Task;

$data = Task::async('testTask', 'list', [12]);

$data = Task::async('testTask', 'delete', [12]); 

Task delivery

 Task::async(string $name, string $method, array $params = [], array $ext = [], int $dstWorkerId = -1, callable $fallback = null) 

Asynchronous task delivery, returning a globally unique task ID

  • Name posting task name
  • Method name of the delivery task
  • The parameters passed by the params task are the parameters of the task method, and the array format is passed.
  • Ext task extension information, will be passed to the task process
  • dstWorkerId The process workerId delivered, the default underlying on-demand process workerId

Task context

The task context and the coroutine task chapter are exactly the same.

Asynchronous task result

There are many situations that do not need to focus on asynchronous task processing results, but there are also some scenarios that need to focus on asynchronous task processing results. The framework provides developers with an event monitoring method to handle asynchronous task results. This event is exactly the same as a normal event. The following definition is event listener:

 use Swoft\Event\Annotation\Mapping\Listener;
use Swoft\Event\EventHandlerInterface;
use Swoft\Event\EventInterface;
use Swoft\Log\Helper\CLog;
use Swoft\Task\TaskEvent;

 * Class FinishListener
 * @since 2.0
 * @Listener(event=TaskEvent::FINISH)
class FinishListener implements EventHandlerInterface
     * @param EventInterface $event
    public function handle(EventInterface $event): void
  • The event must listen to TaskEvent::FINISH
  • If you need to get the data, you can get it from the context. Note that the context object that gets the task completion is not the same as the task object.

Asynchronous task completion context

The context Swoft\Task\FinishContext object can be obtained from the asynchronous task completion listener via the content() global function.

 $taskData = context()->getTaskData();

$taskId = context()->getTaskId();

$taskUniqid = context()->getTaskUniqid();

$server = context()->getServer(); 
  • getTaskData task processing result content
  • getTaskId task ID, corresponding to the Swoole task ID
  • getTaskUniqid Global task unique ID, frame generation, same as the global task ID when the task is delivered
  • getServer Get task Server related information