定时检测websocket服务

20-04-04 14:00 字数 0 阅读 1104 已编辑
<?php

use Swoole\Table;
use Swoole\Timer;
use Swoole\Coroutine\Http\Client;

class CheckPos
{
    /**
     * 定时器间隔时间
     */
    const TIMER_INTERVAL = 30 * 60 * 1000;

    /**
     * 异常邮件触发间隔
     */
    const EMAIL_INTERVAL = 10 * 60;

    private $table;

    public function __construct()
    {
        date_default_timezone_set('Asia/Shanghai');
        $this->table = $this->createTable();
    }

    private function createTable()
    {
        $table = new Table(1024);
        $table->column('send_time', Table::TYPE_STRING, 10);
        $table->create();
        return $table;
    }

    public function schedule()
    {
        Timer::tick(self::TIMER_INTERVAL, function () {
            $this->check();
        });
    }

    private function check()
    {
        $client = new Client('127.0.0.1', 9501);
        $ret = $client->upgrade('/');
        if (!$ret) {
            // 连接异常时发送通知邮件
            $errMsg = sprintf(
                'websocket服务异常,错误状态码:%d,错误信息:%s,当前时间:%s',
                $client->errCode,
                socket_strerror($client->errCode),
                $this->format());
            echo $errMsg . PHP_EOL;
            $this->sendEmail();
        } else {
            echo sprintf('服务正常,当前时间:%s', $this->format());
            echo PHP_EOL;
            $client->close();
        }
    }

    private function sendEmail()
    {
        if ($this->table->exists('email')) {
            $record = $this->table->get('email');
            if ($this->now() - $record['send_time'] > self::EMAIL_INTERVAL) {
                echo '发送邮件...' . PHP_EOL;
                $this->table->set('email', ['send_time' => $this->now()]);
            }
        } else {
            $this->table->set('email', ['send_time' => $this->now()]);
            echo '发送邮件...' . PHP_EOL;
        }
    }

    private function now()
    {
        return time();
    }

    private function format($timestamp = null)
    {
        if (is_null($timestamp)) {
            $timestamp = $this->now();
        }
        return date('Y-m-d H:i:s', $timestamp);
    }
}
$check = new CheckPos();
$check->schedule();
1人点赞>
关注 收藏 改进 举报
1 条评论
排序方式 时间 投票
Up骚年

更新了文章排版

请登录后发表评论