id

Required (workerman >= 3.2.1)

Description:

int Worker::$id

The id number of the current worker process, ranging from 0 to $worker->count-1.

This property is very useful for differentiating worker processes. For example, if a worker instance has multiple processes, and the developer only wants to set a timer in one of the processes, they can do so by identifying the process id. For instance, setting a timer only in the process with id number 0 of that worker instance (see example below).

Note:

The id number remains unchanged after the process restarts.

The assignment of the process id is based on each worker instance. Each worker instance starts numbering its processes from 0, so there will be duplicate process ids between worker instances, but the process ids within a worker instance will not repeat. For example:

<?php
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';

// Worker instance 1 has 4 processes, with process id numbers 0, 1, 2, 3 respectively
$worker1 = new Worker('tcp://0.0.0.0:8585');
// Set to start 4 processes
$worker1->count = 4;
// Each process will print its current process id number after startup, which is $worker1->id
$worker1->onWorkerStart = function($worker1)
{
    echo "worker1->id={$worker1->id}\n";
};

// Worker instance 2 has 2 processes, with process id numbers 0, 1 respectively
$worker2 = new Worker('tcp://0.0.0.0:8686');
// Set to start 2 processes
$worker2->count = 2;
// Each process will print its current process id number after startup, which is $worker2->id
$worker2->onWorkerStart = function($worker2)
{
    echo "worker2->id={$worker2->id}\n";
};

// Run the worker
Worker::runAll();

Output similar to:

worker1->id=0
worker1->id=1
worker1->id=2
worker1->id=3
worker2->id=0
worker2->id=1

Note: Due to the lack of support for setting the number of processes count, Windows systems will only have one id, which is 0. This example cannot run under Windows systems because you cannot initialize two Workers listening on the same file.

Example

A worker instance with 4 processes, setting the timer only on the process with id number 0.

use Workerman\Worker;
use Workerman\Timer;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('tcp://0.0.0.0:8585');
$worker->count = 4;
$worker->onWorkerStart = function($worker)
{
    // Set the timer only on the process with id number 0, no timer is set on processes 1, 2, and 3
    if($worker->id === 0)
    {
        Timer::add(1, function(){
            echo "4 worker processes, timer set only on process 0\n";
        });
    }
};
// Run the worker
Worker::runAll();