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

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

Declaration

<?php OpenSwoole\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 OpenSwoole server.

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

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

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

Last updated on September 20, 2022