How to Use Workerman Timer for Scheduled PHP Tasks

This guide explains how Workerman's Timer runs functions or class methods at set intervals within the same process, showing examples of anonymous‑function timers and configuring timers to run only on specific worker processes.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
How to Use Workerman Timer for Scheduled PHP Tasks

Timer Overview

In Workerman, the Timer component allows you to execute a function or class method at regular intervals. The timer runs inside the current worker process; Workerman does not spawn additional processes or threads for timers.

1. Using an Anonymous Function as the Timer Callback

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

$task = new Worker();
// Number of processes that will run the timer (ensure your logic is safe for concurrency)
$task->count = 1;
$task->onWorkerStart = function (Worker $task) {
    // Execute every 2.5 seconds
    $interval = 2.5;
    Timer::add($interval, function () {
        echo "task run
";
    });
};
// Start the workers
Worker::runAll();

2. Setting a Timer Only on a Specific Worker Process

If a worker instance has multiple processes, you can restrict the timer to a particular process (e.g., the process with ID 0).

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

$worker = new Worker();
$worker->count = 4; // Four worker processes
$worker->onWorkerStart = function (Worker $worker) {
    // Only set the timer on the process whose ID is 0
    if ($worker->id === 0) {
        Timer::add(1, function () {
            echo "4 workers, timer only on process 0
";
        });
    }
};
Worker::runAll();

These examples demonstrate how to schedule recurring tasks with Workerman and how to control which worker processes execute the timer, helping you avoid unintended concurrency issues.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendconcurrencytimerScheduled Tasks
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.