Join 4,000+ others and never miss out on new tips, tutorials, and more.
4.x is outdated, please check the latest version 22.x
Latest version:
pecl install openswoole-22.1.2
<?php Swoole\Server->on('Shutdown', callable $callback)
The event callback name.
Callable event function.
If success, it returns true
, otherwise it returns false
.
Execute the callback function when the server is shutting down. You setup this callback before you start a Swoole 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:
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 Swoole 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.
<?php
$server = new Swoole\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();