OpenSwoole Server taskwait()

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

Declaration

<?php OpenSwoole\Server->taskwait(mixed $data, float $timeout = 0.5, int $dstWorkerId = -1): string|bool

Parameters

data

The data to send to the task worker to process. This can be of any valid PHP variable type. During transmission, data may be temporarily serialized but this will be automatically handled by OpenSwoole.

timeout

The amount of time in seconds to wait for the task to complete, this function won't return until the task is completed or if this timeout is reached, if the timeout is reached, false will be returned. Minimum value is 1ms.

dstWorkerId

Allows you to specify which task worker to send the new task to. By default it is set to -1 which means any available task worker from the pool. But you can pass in a task worker ID number and send a new task to that specific task worker.

Return

string|bool

If the task succeeds, the return is the result of the task, otherwise it returns if the set timeout is reached.

Description

The OpenSwoole\Server->taskwait is similar to OpenSwoole\Server->task. The two methods both send task data to the task worker pool to execute, but taskwait is a blocking operation.

The taskwait function will not return unless the task worker has completed and returned a result or if the timeout is reached, in that case false will be returned. When the timeout is reached, the return from the task will no longer be returned.

From v4.0.4, the taskwait function supports the use of coroutine scheduling, meaning the coroutine schedular will not be blocked when executing concurrent calls to the taskwait function, only the current client will be blocked, not the process, this is true for when you are using OpenSwoole\Server::POOL_MODE mode with coroutines enabled. In OpenSwoole\Server::SIMPLE_MODE mode with no coroutines enabled, this function will block the process while waiting for a return.

However, if the operation inside onTask does not use any I/O or any blocking code, the task can be deemed as non-blocking code because the task doesn't execute anything which would block a process.

You should not call taskwait inside of a task process.

Example

<?php
$server->on('Task', function(OpenSwoole\Server $server, $taskId, $reactorId, $data)
{
    echo "Task Worker Process received data";

    echo "#{$server->worker_id}\tonTask: [PID={$server->worker_pid}]: task_id=$task_id, data_len=" . strlen($data) . "." . PHP_EOL;

    return $data;
});

$server->on('Receive', function (OpenSwoole\Server $server, $fd, $reactorId, $data)
{
    $result = $server->taskwait($data, 1);

    if($result !== false)
    {
        $server->send($fd, "Task finished with saying: $result");
    }
    else
    {
        $server->send($fd, 'Task did not complete in time');
    }
});
Last updated on September 20, 2022