Join 4,000+ others and never miss out on new tips, tutorials, and more.
4.x is outdated, please check the latest version 22.x
Latest version:
pecl install openswoole-22.1.2
<?php Swoole\Server->taskwait(mixed $data, float $timeout = 0.5, int $dstWorkerId = -1): string|bool
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 Swoole.
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.
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.
If the task succeeds, the return is the result of the task, otherwise it returns if the set timeout is reached.
The Swoole\Server->taskwait
is similar to Swoole\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 SWOOLE_PROCESS
mode with coroutines enabled. In SWOOLE_BASE
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.
<?php
$server->on('Task', function(Swoole\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 (Swoole\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');
}
});