OpenSwoole Server stop

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

Declaration

<?php OpenSwoole\Server->stop(int $workerId = -1, bool $waitEvent = false): bool

Parameters

workerId

The Swoole process ID of the worker to stop, default is -1 which means the current worker only

waitEvent

When stopping workers, should the server exit immediately (default) or wait for the event loop to become empty

Return

success

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

Description

Stop current worker processes or worker process by ID, this will trigger the WorkerStop callback function.

Use this method to replace the functions exit/die to end the worker process as an alternative.

After any workers are stopped, the Manager process wil restart those workers again and the WorkerStart event will be triggered.

Stopping a Worker Safely

By default when running $server->stop() it will exit all workers immediately and will not wait for the event loop to become empty. Because a worker at the time may be busy i.e waiting for data to be returned from a MySQL server and the stop event occurs, the database connection result will be lost.

So if you want to stop workers safely you can run $server->stop($workerId, true) instead. Which will wait for the worker to be free and thus, won't affect any ongoing processes.

Example

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

$server->on('connect', function ($server, $fd)
{
    echo "New connection established: #{$fd}.\n";
});

$server->on('receive', function ($server, $fd, $from_id, $data)
{
    if(trim($data) == "stop")
    {
        $server->stop();
    }
    else
    {
        $server->send($fd, "Echo to #{$fd}: \n".$data);
        $server->close($fd);
    }
});

$server->on('WorkerStop', function($server, $worker_id)
{
    echo $worker_id . " stop\n";
});

$server->on('close', function ($server, $fd)
{
    echo "Connection closed: #{$fd}.\n";
});

$server->start();
Last updated on September 1, 2022