# 定时检测websocket服务

**URL:** <https://www.shiqidu.com/t/topic/693>\
**Category:** 开发调优\
**Tags:** Swoole\
**Created:** [2020 年4 月 4 日 06:00 UTC](https://www.shiqidu.com/t/topic/693 "2020-04-04T06:00:21Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

作者： ![danton](https://www.shiqidu.com/user_avatar/www.shiqidu.com/danton/32/489_2.png) [@danton](https://www.shiqidu.com/u/danton)\
发布日期： [2020 年4 月 4 日 06:00 UTC](https://www.shiqidu.com/t/topic/693/1 "2020-04-04T06:00:21Z")

</div>

```php
<?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();

```

---

<div class="post-metadata">

作者： ![Leon](https://www.shiqidu.com/user_avatar/www.shiqidu.com/leon/32/5_2.png) [@Leon](https://www.shiqidu.com/u/Leon)\
发布日期： [2020 年4 月 11 日 13:04 UTC](https://www.shiqidu.com/t/topic/693/2 "2020-04-11T13:04:48Z")

</div>

更新了文章排版
