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

Declaration

<?php
Swoole\Server->on('WorkerExit', 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 a Worker Process is exciting. This event is triggered before the actual worker is stopped, allowing you to tell the worker to do something before its process is terminated. Like closing connections safely, saving logs or saving buffer data to the database etc. This event is triggered before WorkerStop.

A worker process could also be a task worker, you can check by seeing the boolean value of $server->taskworker.

Example

Before these examples, if you need to see how a full working server is setup see the onStart event.

The WorkerExit event is executed before the WorkerStop event and is only effective when you have enabled the hot code reloading functionality with a Swoole server.

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

// This event callback gets passed the server object and the worker process ID (Not the PID)
$server->on('WorkerExit', function(Swoole\Server $server, int $workerId)
{
    // ...
});

The WorkerExit event will not be triggered if the process is forcefully terminated.