Backend Development 6 min read

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

onWorkerStart = function () {
    // Execute at the 1st second of every minute
    new Crontab('1 * * * * *', function () {
        echo date('Y-m-d H:i:s') . "\n";
    });
    // Execute daily at 07:50 (seconds omitted)
    new Crontab('50 7 * * *', function () {
        echo date('Y-m-d H:i:s') . "\n";
    });
    // Execute every 2.5 seconds
    $time_interval = 2.5;
    Timer::add($time_interval, function () {
        echo "task run\n";
    });
};
Worker::runAll();

// Destroy a timer
$crontab = new Crontab('1 * * * * *', function () {
    echo date('Y-m-d H:i:s') . "\n";
});
$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 . "\n";
});

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

// 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.

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}\n{$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}\n";
        $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') . "\n";
        });
    }

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

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

    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.

backendSchedulingPHPTimerSwooleWorkerman
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

login 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.