Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Swoole Task instance


May 14, 2021 Swoole


Table of contents


Introduction to Swoole Task asynchronous tasks

Swoole's asynchronous task task task task task system can be convenient for us to invoke the execution of asynchronous tasks during development without waiting.

Common usage scenarios:

The task module is used to do some asynchronous slow tasks, such as webim medium broadcast, sending mail, asynchronous order processing, asynchronous payment processing, etc.

  • The task process must be blocked synchronously
  • The task process supports timers

node.js If there were 100,000 connections, when you want to broadcast, it would loop 100,000 times, when the program can't do anything, can't accept new connections, can't send and receive packages.

In the case of swoole, the worker process can continue processing new data requests after it has been dropped to the task process. When the task is complete, the worker process is asynchronously notified that the task has been completed.

Of course, the task module does more than that, implementing PHP database connection pools, asynchronous queues, etc., and needs further mining.

A simple example:

$serv = new Swoole\Server("127.0.0.1", 9502);
$serv->set(array('task_worker_num' => 4));
$serv->on('Receive', function($serv, $fd, $from_id, $data) {
    $task_id = $serv->task("Async");
    echo "Dispath AsyncTask: id=$task_id\n";
});
$serv->on('Task', function ($serv, $task_id, $from_id, $data) {
    echo "New AsyncTask[id=$task_id]".PHP_EOL;
    $serv->finish("$data -> OK");
});
$serv->on('Finish', function ($serv, $task_id, $data) {
    echo "AsyncTask[$task_id] Finish: $data".PHP_EOL;
});
$serv->start();

swoole_server the task asynchronous task

Post an asynchronous task to task_worker pool. T his function is non-blocked and returns immediately after execution. The worker process can continue to process new requests.

int swoole_server::task(mixed $data, int $dst_worker_id = -1) 
$task_id = $serv->task("some data");
//swoole-1.8.6或更高版本
$serv->task("taskcallback", -1, function (swoole_server $serv, $task_id, $data) {
    echo "Task Callback: ";
    var_dump($task_id, $data);
});
  • $data the task data to be posted, it can be any PHP variable other than the resource type
  • $dst can be used to determine which task process to deliver to, the incoming ID is available, with a range of 0 - (serv->task_worker_num -1)
  • The call was successful and returned a value of $task_id the ID of this task. If there is a finish onFinish callback $task_id parameter
  • The call failed and the return value is false
  • The target Task process is not specified, and calling the Task method determines the free and busy state of the Task process, with the underlying only posting tasks to the idle Task process
  • Version 1.8.6 adds a third argument, you can onFinish the task sets a callback function, the Task returns the result by executing the set callback function directly and no onFinish callback

$dst is available after 1.6.11 plus, defaulting to random delivery
$task id is an integer from 0-42 billion and is unique within the current process
The task method cannot be called in the task process/user-defined process

This feature is used to perform slow tasks asynchronously, such as a chat room server, which can be used to send broadcasts. W hen the task is complete, calling $serv->finish("finish") the task process tells the worker process that the task is complete. Of swoole_server->finish optional.

Task underlying communication using the Unix Socket pipeline is full memory and has no IO consumption. Single-process read-and-write performance of up to 1 million/s, different processes use different pipeline communication, can maximize the use of multi-core.

The AsyncTask feature was added in version 1.6.4 and does not start the task by default and needs to be task_worker_num manually set up
task_worker number of swoole_server is adjusted in the task_worker_num::set parameter, such as task_worker_num , which means that 64 processes are started to receive asynchronous tasks

Configuration parameters

swoole_server-taskwait/finish 3 methods enable temporary files to be $data data exceeds 8K. A warning is thrown at the bottom when the contents of package_max_length content exceed the server->package_max_length

WARN: task package is too big.

Server-gt;package_max_length default is 2M

Precautions

  • With swoole_server_task you must set the onTask and onFinish callbacks for the server, or swoole_server-start will fail
  • The number of task operations must be less than the onTask processing speed, and if the delivery capacity exceeds the processing capacity, the task will fill the cache, causing the worker process to become blocked. The worker process will not be able to receive new requests
  • Task delivery tasks cannot be used in user processes added using addProcess, use the sendMessage interface to communicate with the work process

Swoole taskwait

Function prototype:

string $result = swoole_server->taskwait(mixed $task_data, float $timeout = 0.5, int $dst_worker_id = -1);

Taskwait has the same function as the task method, which is used to post an asynchronous task to the task process pool. Unlike task, taskwait is blocked waiting until the task is completed or timed back.

$result result of the execution of the task, issued by the $serv-gt;finish function. If this task times out, the false is returned here.

Taskwait is a blocking interface, if your server is fully asynchronous please use swoole_server:: task and swoole_server::: finish, do not use taskwait
The third parameter can determine which task to deliver to, the incoming ID, the range is 0 - serv-gt;task_worker_num
$dst is available after 1.6.11 plus, defaulting to random delivery
The taskwait method cannot be called in the task process

onTask

called task_worker process within the process. T he worker process can swoole_server_task a function to task_worker new tasks to the worker process. The current Task process switches the process state to Busy when onTask callback function is called, the new Task is no longer onTask the process state is switched to idle and then continues to receive the new Task.

function onTask((swoole_server $serv, int $task_id, int $src_worker_id, string $data));
  • $task id is a task ID that is automatically generated within the swoole extension to distinguish between different tasks. $task the combination of src_worker_id and $is globally unique, and the task IDs posted by different worker processes may be the same
  • $src worker_id comes from which worker process
  • $data is the content of the task

Returns the execution results to the worker process

Versions above 1.7.2, in the onTask function, return string, indicate that this content is returned to the worker process. The onFinish function is triggered in the worker process to indicate that the posted task is complete.

  • The return variable can be any non-null PHP variable

In previous versions of 1.7.2, swoole_server->finish() was called to return the result to the worker process