Swoole\Server->on('Finish', fn)

Declaration

<?php
Swoole\Server->on('Finish', Callable $callback)

Parameters

event

The event callback name.

callback

Callable event function.

Return

success

If success, it returns true, otherwise it returns false.

Description

This callback function is executed when a task from the task worker pool has finished, the result sending back to the caller worker process will trigger this event, allowing you to process any returned data.

You are not required to return data from a completed task but it allows you to act on a task outcome and run tasks asynchronously without having to wait for the task to complete in the worker process which is handling a server request.

Example

<?php
$server = new Swoole\Server("127.0.0.1", 9501, SWOOLE_PROCESS);

// Setup the rest of the server...

$server->on('Task', function(Swoole\Server $server, Swoole\Server\Task $task)
{
    // Show the task data
    var_dump($task);

    // Complete the task and return a result which will trigger the `Finish` event, running a task asynchronously
    $task->finish([123, 'hello']);
});

$server->on('Finish', function (Swoole\Server $server, int $taskId, mixed $data)
{
    echo "Task#$task_id finished, data_len=" . strlen($data) . PHP_EOL;
});
  • $server: The Swoole server object
  • $taskId: the ID number of task worker
  • $data: The result of task that completed and returned data

Notes

  • The Finish event will only be triggered when the task process either uses $task->finish or returns data within its callback

  • The execution of the task result is done within the worker process which sent the task initially and the current worker which is handling the server request