Implementing High‑Precision Timers in PHP with Workerman and Swoole

This article explains why traditional crontab cannot meet second‑ or millisecond‑level scheduling requirements in PHP projects and demonstrates how to use Workerman and Swoole timers, including code examples for one‑time, recurring, and task‑based executions.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Implementing High‑Precision Timers in PHP with Workerman and Swoole

Traditional OS crontab tasks lack second‑ or millisecond‑level granularity and are not well suited for high‑precision scheduling in PHP applications.

The article introduces PHP's powerful millisecond timer capabilities and presents two timer extensions (Workerman and Swoole) that can be installed to achieve fine‑grained scheduling.

Workerman Timer Example

<?php
use Workerman\Worker;
use app\api\controller\Cron;
use Workerman\Crontab\Crontab;

require __DIR__ . '/../../../vendor/autoload.php';
$worker = new Worker();
// Set timezone to avoid mismatched results
date_default_timezone_set('PRC');
$worker->onWorkerStart = function () {
    // Execute at the 1st second of every minute
    new Crontab('1 * * * * *', function () {
        echo date('Y-m-d H:i:s') . "
";
    });
    // Execute daily at 07:50 (seconds omitted)
    new Crontab('50 7 * * *', function () {
        echo date('Y-m-d H:i:s') . "
";
    });
    // Execute every 2.5 seconds
    $time_interval = 2.5;
    Timer::add($time_interval, function () {
        echo "task run
";
    });
};
Worker::runAll();

// Destroy a timer
$crontab = new Crontab('1 * * * * *', function () {
    echo date('Y-m-d H:i:s') . "
";
});
$crontab->destroy();
?>

Swoole Timer Example

// Execute a callback every 30 seconds
swoole_timer_tick(30000, function ($timer) use ($task_id) {
    $memPercent = 1000;
    echo date('Y-m-d H:i:s') . '当前值:' . $memPercent . "
";
});

// Execute once after 2 minutes
swoole_timer_after(120000, function () use ($str) {
    echo "send report, $str
";
});

// Clear a timer
swoole_timer_clear(int $timer_id);

The article also provides a complete Swoole server example that demonstrates how to start a server, handle connections, receive data, and integrate timer‑based tasks within the onTask callback.

<?php
namespace Test\Swoole;
use swoole_server;

class Task {
    protected $serv;
    protected $host = '127.0.0.1';
    protected $port = 9501;
    protected $taskName = 'swooleTask';
    protected $pidPath = '/run/swooletask.pid';
    protected $options = [
        'worker_num' => 4,
        'daemonize' => true,
        'log_file' => '/data/log/swoole-task.log',
        'log_level' => 0,
        'dispatch_mode' => 1,
        'task_worker_num' => 4,
        'task_ipc_mode' => 3,
    ];

    public function __construct($options = []) {
        date_default_timezone_set('PRC');
        $this->serv = new swoole_server($this->host, $this->port);
        if (!empty($options)) {
            $this->options = array_merge($this->options, $options);
        }
        $this->serv->set($this->options);
        $this->serv->on('Start', [$this, 'onStart']);
        $this->serv->on('Connect', [$this, 'onConnect']);
        $this->serv->on('Receive', [$this, 'onReceive']);
        $this->serv->on('Task', [$this, 'onTask']);
        $this->serv->on('Finish', [$this, 'onFinish']);
        $this->serv->on('Close', [$this, 'onClose']);
    }

    public function start() {
        $this->serv->start();
    }

    public function onStart($serv) {
        cli_set_process_title($this->taskName);
        $pid = "{$serv->master_pid}
{$serv->manager_pid}";
        file_put_contents($this->pidPath, $pid);
    }

    public function onConnect($serv, $fd, $from_id) {
        $serv->send($fd, "Hello {$fd}!");
    }

    public function onReceive(swoole_server $serv, $fd, $from_id, $data) {
        echo "Get Message From Client {$fd}:{$data}
";
        $res['result'] = 'success';
        $serv->send($fd, json_encode($res));
        $serv->task($data);
    }

    public function onTask(swoole_server $serv, $task_id, $from_id, $data) {
        swoole_timer_tick(30000, function ($timer) use ($task_id) {
            echo date('Y-m-d H:i:s') . "
";
        });
    }

    public function onFinish(swoole_server $serv, $task_id, $data) {}

    public function onClose($serv, $fd, $from_id) {
        echo "Client {$fd} close connection
";
    }

    public function stop() {
        $this->serv->stop();
    }
}
?>

By leveraging these timer mechanisms, developers can implement precise, high‑performance scheduled tasks in PHP without relying on the limited granularity of traditional cron jobs.

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.

BackendtimerSwooleWorkerman
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

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.