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.
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
