Swoole Server taskWaitMulti()

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

Declaration

<?php Swoole\Server->taskWaitMulti(array $tasks, float $timeout = 0.5): bool|array

Parameters

tasks

An array of data which will be sent to a number of task workers to process each element of the array. Each element will be a new task and each task will be executed concurrently. The array must be numerically indexed, no associated arrays.

timeout

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

Return

bool|array

As multiple tasks are executed based on a numerically indexed array, the result if successful will be a numerically indexed array in the same order of the data. So $tasks[2] will have its result at $result[2]. If the timeout is reached, false is returned but a timeout will not affect other tasks which have completed in time, in that case an array of results is returned but the timed out task will not be included.

Description

Execute multiple tasks concurrently based on a numerically indexed array. This method is asynchronous but does not support coroutines by default, you have to use taskCo to create a coroutine environment. By calling this method, it may lead to other suspended coroutines to start as calling this method blocks the process until the result is returned.

The maximum number of concurrent tasks must not exceed 1024 in your array of data and you should not use this method within the server onFinish callback event. If the task workers are all occupied, any new tasks are queued up and will wait until a task finishes before starting a new one.

Example

<?php
$tasks[] = mt_rand(1000, 9999); // Task 1
$tasks[] = mt_rand(1000, 9999); // Task 2
$tasks[] = mt_rand(1000, 9999); // Task 3

// Show all the task data which will be sent
var_dump($tasks);

// Execute 3 tasks concurrently and set the timeout to 10 seconds
$results = $server->taskWaitMulti($tasks, 10.0);

// Tasks which timed out will not be included int he results
if (!isset($results[0]))
{
    echo "Task 1: timeout.\n";
}

// Tasks which completed within the timeout keep the same index in the result
if (isset($results[1]))
{
    echo "Task 2: {$results[1]}\n";
}

if (isset($results[2]))
{
    echo "Task 3: {$results[2]}\n";
}
Last updated on August 31, 2022