Millisecond Timer for Swoole Learning

Keywords: PHP crontab Linux Javascript

I. Setting Timer

We usually use the timer crontab which comes with Linux system to handle the more routine timing tasks, but sometimes it can not meet our business needs, not up to the level of milliseconds, but Swoole can help us achieve.

Let's take a look at Swoole's Official Documents Guide - > Quick Start - >. set timer

swoole provides a JavaScript-like setInterval/setTimeout asynchronous high-precision timer with a granularity of milliseconds. It's also very simple to use.

  • The swoole_timer_tick function is equivalent to setInterval and is triggered continuously.
  • The swoole_timer_after function is equivalent to setTimeout, triggered only once at the agreed time.
  • The swoole? Timer? Tick and swoole? Timer? After functions return an integer representing the ID of the timer

This timer can be cleared using swoole_timer_clear with the timer ID parameter

2. Code Implementation

ws_timer.php

<?php

/**
 * WS Optimizing Basic Class Library
 */

class Ws
{
    public $ws = null;

    CONST HOST = "0.0.0.0";
    CONST PORT = 80;

    public function __construct()
    {
        // static::HOST, static::PORT
        $this->ws = new swoole_websocket_server("0.0.0.0", 80);

        $this->ws->set(
            [

               'enable_static_handler' => true, // Static resource-related settings
               'document_root' => "/work/study/code/swoole/demo/static", // Storing static resource paths
              // 'worker_num' => 2,
              // 'task_worker_num' => 2,
            ]
        );

        $this->ws->on("open", [$this, "onOpen"]);
        $this->ws->on("message", [$this, "onMessage"]);
       // $this->ws->on("task", [$this, "onTask"]);
       // $this->ws->on("finish", [$this, "onFinish"]);
        $this->ws->on("close", [$this, "onClose"]);

        $this->ws->start();
    }

    /**
     * Listening for ws connection events
     * @param $ws
     * @param $request
     */
    public function onOpen($ws, $request)
    {
        print_r("Open:" . $request->fd ."\n");

        // Use timed tasks
        if($request->fd == 1)
        {
            // Execute every 2 seconds
            swoole_timer_tick(2000, function($timer_id){
                echo "2s:timerId:{$timer_id}";
            });

        }
    }

    /**
     * Listening for ws connection messages
     * @param $ws
     * @param $frame
     */
    public function onMessage($ws, $frame)
    {
        echo "ser-push-message:{$frame->data}\n";

        // TODO:: Joining our business requires more than 10 seconds of execution, so task asynchrony can be used here to handle it.
        $data = [
            'task' => 1,
            'fd' => $frame->fd,
        ];

        // Delivery of a task
        // $ws->task($data);

        // Timing task, 5 s later, this is an asynchronous task, not blocking, here using closures
        swoole_timer_after(5000, function() use ($ws, $frame){
            echo "5s-after\n";
            $ws->push($frame->fd, "server-time-after");

        });


        $ws->push($frame->fd, "server-push:".date("Y-m-d H:i:s"));

    }

    /**
     * Delivery task
     *
     * @param $serv
     * @param $taskId
     * @param $workerId
     * @param $data
     */
    public function onTask($serv, $task_id, $from_id, $data)
    {
        // Time-consuming scenario 10s
        sleep(10);

        return "on task finish";  // Tell worker
    }

    public function onFinish($serv, $task_id, $data)
    {
        echo "taskId:{$task_id}\n";

        // Note: This $data parameter is the result returned by the onTask method: on task finish, not the onTask method parameter.
        echo "finish-data-success:{$data}\n";

    }

    /**
     * Listening for WebSocket Connection Closure Events
     *
     * @param $ws
     * @param $fd
     */
    public function onClose($ws, $fd)
    {
        echo "clientid-{$fd} is closed \n";
    }
}

$ws_obj = new Ws();

Execute the script on the server side:

root@5ee6bfcc1310:/work/study/code/swoole/demo/server# php ws_timer.php
Open:3
ser-push-message:Hello-Lily
clientid-1 is closed
5s-after
clientid-2 is closed

Execute client code in browser: ws_task_client.html

We can see that after opening the browser, after 5 seconds, the server pushes the server-time-after information to the client through a timed task.

Posted by markdr on Fri, 04 Oct 2019 08:27:03 -0700