您的位置 首页 php

除了Crontab,Swoole Timer也可以实现定时任务的

一般的定时器是怎么实现的呢?我总结如下:

1.使用Crontab工具,写一个shell脚本,在脚本中调用PHP文件,然后定期执行该脚本;

2.ignore_user_abort()和set_time_limit()配合使用;

3.pcntl_alarm;

4.swoole异步毫秒定时器

Timer做定时器,直接上代码~~

服务端代码( server .php)

 <?php
/*
 swoole Task运行实例
 Task简介
 Swoole的业务逻辑部分是同步阻塞运行的,如果遇到一些耗时较大的操作,例如访问数据库、广播消息等,就会影响服务器的响应速度。因此Swoole提供了Task功能,将这些耗时操作放到另外的进程去处理,当前进程继续执行后面的逻辑.
 运行Task,需要在swoole服务中配置参数 task_worker_num,即可开启task功能。此外,必须给swoole_server绑定两个回调函数:onTask和onFinish。这两个回调函数分别用于执行Task任务和处理Task任务的返回结果。
*/
class server{
     private  $serv;

    /**
     * [__construct description]
     * 构造方法中,初始化 $serv 服务
     */    public  function  __construct() {
        $this->serv = new swoole_server('0.0.0.0', 9501);
        //初始化swoole服务
        $this->serv->set(array(
            'worker_num'  => 8,
            'daemonize'   => false, //是否作为守护进程,此配置一般配合log_file使用
            'max_request' => 1000,
            'log_file'    => './swoole.log',
            'task_worker_num' => 8
        ));

        //设置监听
        $this->serv->on(' start ', array($this, 'onStart'));
        $this->serv->on(' Connect ', array($this, 'onConnect'));
        $this->serv->on("Receive", array($this, 'onReceive'));
        $this->serv->on(" Close ", array($this, 'onClose'));
        $this->serv->on("Task", array($this, 'onTask'));
        $this->serv->on("Finish", array($this, 'onFinish'));

        //开启 
        $this->serv->start();
    }

    public function onStart($serv) {
        echo SWOOLE_VERSION . " onStart\n";
    }

    public function onConnect($serv, $fd) {
        echo $fd."Client Connect.\n";
    }

    public function onReceive($serv, $fd, $from_id, $data) {
        echo "Get Message From Client {$fd}:{$data}\n";
        // send a task to task worker.
        $param = array(
            'fd' => $fd
        );
        // start a task
        $serv->task(json_encode($param));

        echo "Continue Handle Worker\n";
    }

    public function onClose($serv, $fd) {
        echo "Client Close.\n";
    }

    public function onTask($serv, $task_id, $from_id, $data) {
        echo "This Task {$task_id} from Worker {$from_id}\n";
        echo "Data: {$data}\n";
        for($i = 0 ; $i < 2 ; $i ++ ) {
            sleep(1);
            echo "Task {$task_id} Handle {$i} times...\n";
        }
        $fd = json_decode($data, true);
        $serv->send($fd['fd'] , "Data in Task {$task_id}");
        return "Task {$task_id}'s result";
    }

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

$server = new server();  

客户端代码(client.php)

 <?php
class Client{
    private $client;

    public function __construct() {
        $this->client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
        $this->client->on('Connect', array($this, 'onConnect'));
        $this->client->on('Receive', array($this, 'onReceive'));
        $this->client->on('Close', array($this, 'onClose'));
        $this->client->on('Error', array($this, 'onError'));
    }

    public function connect() {
        if(!$fp = $this->client->connect("127.0.0.1", 9501 , 1)) {
            echo "Error: {$fp->err Msg }[{$fp->errCode}]\n";
            return;
        }
    }

    //connect之后,会调用onConnect方法
    public function onConnect($cli) {
        fwrite(STDOUT, "Enter Msg:");
        swoole_event_add(STDIN,function(){
            fwrite(STDOUT, "Enter Msg:");
            $msg = trim(fgets(STDIN));
            $this->send($msg);
        });
    }

    public function onClose($cli) {
        echo "Client close connection\n";
    }

    public function onError() {

    }

    public function onReceive($cli, $data) {
        echo "Received: ".$data."\n";
    }

    public function send($data) {
        $this->client->send($data);
    }

    public function isConnected($cli) {
        return $this->client->isConnected();
    }

}

$client = new Client();
$client->connect();  

运行服务端: php server.php

运行客户端: php client.php

结果:

服务端

客户端:

领取方式:点赞关注小编后私信【资料】获取资料领取方式!

部分资料展示:

前60名限时精品福利:

分布式消息中间件及多进程实战

Redis缓存击穿/缓存雪崩预防策略

腾讯高级PHP工程师精品笔试题

Swoole并发百万的协程使用及分析

领取方式:点赞关注小编后私信【资料】获取资料领取方式!

文章来源:智云一二三科技

文章标题:除了Crontab,Swoole Timer也可以实现定时任务的

文章地址:https://www.zhihuclub.com/151060.shtml

关于作者: 智云科技

热门文章

网站地图