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

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

Declaration

<?php OpenSwoole\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 OpenSwoole\Server("127.0.0.1", 9501, OpenSwoole\Server::POOL_MODE);

// Setup the rest of the server...

$server->on('Task', function(OpenSwoole\Server $server, OpenSwoole\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 (OpenSwoole\Server $server, int $taskId, mixed $data)
{
    echo "Task#$task_id finished, data_len=" . strlen($data) . PHP_EOL;
});
  • $server: The OpenSwoole 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

Last updated on September 20, 2022