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

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

Declaration

<?php OpenSwoole\Server->on('Shutdown', callable $callback)

Parameters

event

The event callback name.

callback

Callable event function.

Return

success

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

Description

Execute the callback function when the server is shutting down. You setup this callback before you start a OpenSwoole server, see the example to see how to properly use this callback. This event happens during a normal shutdown procedure, so it won't run if the server is forcefully shutdown.

Before the Shutdown event, the following steps are completed:

  • All Master and Manager threads are stopped
  • All the Worker-sub processes are stopped
  • All Task processes and User defined processes are stopped
  • The TCP/UDP ports is closed and the server is no longer listening on the network
  • The reactor/event loop is closed
  • TCP heartbeat thread is stopped, so are any UDP receiving threads

Force killing a process using kill -9, doesn't trigger the callback function for Shutdown. Use the signal SIGTREM and kill -15 instead, so that the shutdown event is triggered. On the command line, you can perform Ctrl+C to shutdown the OpenSwoole server without triggering the shutdown server event.

Warning

When the shutdown event is called, you must not execute any asynchronous code or perform any coroutine operations as at this stage there is no environment to support this logic as most of the server loops and processes have been stopped, only use this event to perform post-server tasks, like cleanup, logs etc.

Example

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

$server->on('start', function ($server)
{
    echo "Server has started.\n";
});

$server->on('shutdown', function ($server)
{
    echo "Server is shutting down.\n";
});

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

$server->on('receive', function ($server, $fd, $fromId, $data)
{
    $server->send($fd, "Echo to #{$fd}: \n".$data);
    $server->close($fd);
});

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

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