Heartbeat logic: check connection health here
@return void
@throws \PhpAmqpLib\Exception\AMQPRuntimeException
499485
public function check_heartbeat()
    {
        // ignore unless heartbeat interval is set
        if ($this->heartbeat !== 0 && $this->last_read && $this->last_write) {
            $t = microtime(true);
            $t_read = round($t - $this->last_read);
            $t_write = round($t - $this->last_write);

            // server has gone away
            if (($this->heartbeat * 2) < $t_read) {
                $this->close();
                throw new AMQPHeartbeatMissedException('Missed server heartbeat');
            }

            // time for client to send a heartbeat
            if (($this->heartbeat / 2) < $t_write) {
                $this->write_heartbeat();
            }
        }
    }
1322920
public static function checkNeeded(): void
    {
        set_time_limit(0);
        ignore_user_abort(true);
        ini_set('memory_limit', '1G');

        $services_collection = new ServiceEntityRepository;
        $services_collection
            ->setWhereRunning(0)
            ->setWhereAutoStart(1);

        /** @var ServiceEntity $service_entity */
        foreach ($services_collection->getAsArrayOfObjects() as $service_entity) {
            if (NOW - $service_entity->getLastTs() >= $service_entity->getPeriod()) {
                self::run($service_entity->getId());
            }
        }
    }
843699
public function Connected() {
    if(!empty($this->smtp_conn)) {
      $sock_status = socket_get_status($this->smtp_conn);
      if($sock_status["eof"]) {
        // the socket is valid but we are not connected
        if($this->do_debug >= 1) {
            $this->edebug("SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected");
        }
        $this->Close();
        return false;
      }
      return true; // everything looks good
    }
    return false;
  }
245456
protected function checkProcessStatus(): void
    {
        $this->logProcessStandardStreams();

        $process = $this->process;

        if (!empty($process->getErrorOutput())) {
            if (IdleTimeoutException::exceptionApplies($process)) {
                throw new IdleTimeoutException(
                    $this->options['idle_timeout'],
                    new NodeFatalException($process, $this->options['debug'])
                );
            } else if (NodeFatalException::exceptionApplies($process)) {
                throw new NodeFatalException($process, $this->options['debug']);
            } elseif ($process->isTerminated() && !$process->isSuccessful()) {
                throw new ProcessFailedException($process);
            }
        }

        if ($process->isTerminated()) {
            throw new Exceptions\ProcessUnexpectedlyTerminatedException($process);
        }
    }
932834
public function check(): bool
  {
    if ( $this->current !== null ){
      // if $on_error is set to E_CONTINUE returns true
      if ( $this->on_error === self::E_CONTINUE ){
        return true;
      }
      // If any connection has an error with mode E_STOP_ALL
      if ( self::$has_error_all && ($this->on_error !== self::E_STOP_ALL) ){
        return false;
      }
      // If this connection has an error with mode E_STOP
      if ( $this->has_error && ($this->on_error !== self::E_STOP) ){
        return false;
      }
      return true;
    }
    return false;
  }
128497
private function checkStatus()
    {
        if (!$this->running) {
            return;
        }

        if ($this->running) {
            foreach (proc_get_status($this->resource) as $key => $value) {
                if ($key == 'command') {
                    continue;
                }

                $this->$key = $value;
            }
        }

        if (!$this->running) {
            $this->cleanup();
        }
    }
441353
@Override
    public void heartbeat() throws IOException {
        isOpen();
        int ret = WDT.ping(fd);
        if(ret<0) {
            throw new IOException("Heartbeat error. File " + filename + " got " + ret + " back.");
        }
    }
248130
def _raise_or_append_exception(self):
        
        message = (
            'Connection dead, no heartbeat or data received in >= '
            '%ds' % (
                self._interval * 2
            )
        )
        why = AMQPConnectionError(message)
        if self._exceptions is None:
            raise why
        self._exceptions.append(why)
614663
public function connected()
	{
		$this->connect();

		if (\is_resource($this->connection))
		{
			return pg_ping($this->connection);
		}

		return false;
	}
35600
public function onReady()
    {
        if ($this->pool->config->protologging->value) {
            Daemon::log("New connection\n\n");
        }
        $e = explode('.', $this->protover);
        $packet = pack('nn', $e[0], $e[1]);

        if (strlen($this->user)) {
            $packet .= "user\x00" . $this->user . "\x00";
        }

        if (strlen($this->dbname)) {
            $packet .= "database\x00" . $this->dbname . "\x00";
        }
        elseif (strlen($this->path)) {
            $packet .= "database\x00" . $this->path . "\x00";
        }

        if (strlen($this->options)) {
            $packet .= "options\x00" . $this->options . "\x00";
        }

        $packet .= "\x00";
        $this->sendPacket('', $packet);
    }
876885
public function actionStatus()
    {
        $pid = $this->getMasterPid();
        Console::stdout("beyod($pid) is running ...\r\n");
        Console::stdout("php ini: ".php_ini_loaded_file()."\r\n");
        Console::stdout("php version: ".phpversion()."\r\n");
        Console::stdout("necessary extensions status:\r\n");
        foreach(['pcntl', 'event', 'posix'] as $ext){
            Console::stdout("\t$ext: \t". (extension_loaded($ext) ? 'yes':'no')."\r\n");
        }
    }
497595
def ensure_connected(self):
        """"""
        if not self.is_connected():
            if not self._auto_connect:
                raise DBALConnectionError.connection_closed()
            self.connect()
1206267
public function connect()
    {
        /*
         The Server MUST process a second CONNECT Packet sent from a Client as a protocol violation
         and disconnect the Client [MQTT-3.1.0-2]

         So CONNECT SHOULD be a blocking connection.
         */
        $this->socket->connect(function ($cli) {
            Debug::Log(Debug::INFO, 'connect(): Connection established.');
            /**
             * @var Message\CONNECT $connectobj
             */
            $connectobj = $this->getMessageObject(Message::CONNECT);

            if (!$this->connect_clean && empty($this->clientid)) {
                throw new Exception('Client id must be provided if Clean Session flag is set false.');
            }

            # default client id
            if (empty($this->clientid)) {
                $this->clientid = 'mqtt' . substr(md5(uniqid('mqtt', true)), 8, 16);
            } else {
                $connectobj->setClientId($this->clientid);
            }
            Debug::Log(Debug::DEBUG, 'connect(): clientid=' . $this->clientid);

            $connectobj->setKeepalive($this->keepalive);
            Debug::Log(Debug::DEBUG, 'connect(): keepalive=' . $this->keepalive);

            $connectobj->setAuth($this->username, $this->password);
            Debug::Log(Debug::DEBUG, 'connect(): username=' . $this->username . ' password=' . $this->password);

            $connectobj->setClean($this->connect_clean);

            if ($this->connect_will instanceof Will) {
                $connectobj->setWill($this->connect_will);
            }

            $length = 0;

            $bytes_written = $this->message_write($connectobj, $length);
            Debug::Log(Debug::DEBUG, 'connect(): bytes written=' . $bytes_written);

            $this->keepalive_time = swoole_timer_tick($this->keepalive * 500, [$this, 'keepalive']);
        }, [$this, 'onReceive'],function (){
            secho("MQTT", "连接mqtt服务器失败,正在重试");
            swoole_timer_after(1000,[$this,'connect']);
        },function (){
            if ($this->keepalive_time!=null) {
                swoole_timer_clear($this->keepalive_time);
                $this->keepalive_time = null;
            }
            $this->connect();
        });
    }
945443
@Override
    protected void checkIfHeartbeatSkipped(String name, EventChannelStruct channelStruct) {
            // Check if heartbeat have been skipped, can happen if
            // 1- the server is dead
            // 2- The network was down;
            // 3- The server has been restarted on another host.

        if (KeepAliveThread.heartbeatHasBeenSkipped(channelStruct)) {
            DevError    dev_error = null;
            try{
                String  admDeviceName = channelStruct.adm_device_proxy.fullName();  //.toLowerCase();
                //  Since Tango 8.1, heartbeat is sent in lower case.
                if (channelStruct.getTangoRelease()>=810)
                    admDeviceName = admDeviceName.toLowerCase();
                channelStruct.adm_device_proxy = new DeviceProxy(admDeviceName);
                channelStruct.adm_device_proxy.set_timeout_millis(300);
                channelStruct.adm_device_proxy.ping();
                reconnectToChannel(name);
            }
            catch (DevFailed e) {
                dev_error = e.errors[0];
            }

            Enumeration callbackStructs = EventConsumer.getEventCallbackMap().elements();
            while (callbackStructs.hasMoreElements()) {
                EventCallBackStruct callbackStruct = (EventCallBackStruct) callbackStructs.nextElement();
                if (callbackStruct.channel_name.equals(name)) {
                    //	Push exception
                    if (dev_error != null)
                        pushReceivedException(channelStruct, callbackStruct, dev_error);
                    else {
                        //  ToDo Re connect without error means heartbeat missing
                        dev_error = new DevError("API_NoHeartbeat",
                                ErrSeverity.ERR, "No heartbeat from " +
                                    channelStruct.adm_device_proxy.get_name(),
                                "ZmqEventConsumer.checkIfHeartbeatSkipped()");
                        pushReceivedException(channelStruct, callbackStruct, dev_error);
                    }

                    //	If reconnection done, try to re subscribe
                    //		and read attribute in synchronous mode
                    if (reconnectToEvent(channelStruct, callbackStruct)) {
                        if (!callbackStruct.event_name.equals(eventNames[DATA_READY_EVENT])) {
                            readAttributeAndPush(channelStruct, callbackStruct);
                        }
                    }
                }
            }
        }
    }
994136
public function heartBeat()
    {
        if (!$this->request->isAll(['ajax', 'post'])) {
            throw new MethodNotAllowedException();
        }

        $loginTime = $this->request->session()->check('loginTime') ? $this->request->session()->read('loginTime') : 0;
        $maxLoggedInTime = (int)Wasabi::setting('Core.Login.HeartBeat.max_login_time', 0) / 1000;
        $logoutTime = $loginTime + $maxLoggedInTime;

        if (time() <= $logoutTime) {
            $this->set([
                'status' => 200,
                '_serialize' => ['status']
            ]);
        } else {
            $this->Auth->logout();

            $this->set([
                'status' => 401,
                '_serialize' => ['status']
            ]);
        }
    }
868522
public function health()
    {
        try {
            // Logic for validating health (e.g. connections to external
            // services) should go here.

            // If a cache driver is defined, check it is working.
            if (!empty(env('CACHE_DRIVER', null))) {
                Cache::put('health_check', 'test', 1);
                Cache::get('health_check');
            }

            // If a DB connection is defined, check it is working.
            if (!empty(env('DB_HOST', null))) {
                DB::connection()->getPdo();
            }

            // All of our service dependencies are working so build a valid
            // response object.
            return $this->generateResponse('health', null);
        } catch (\Exception $e) {
            return $this->generateResponse('', null, 500, Status::FAIL, $e->getMessage());
        }
    }
572970
protected function shouldBeConnected()
    {
        // If we lost the connection, first let's try and reconnect
        if (!$this->isConnected()) {
            try {
                $this->switchNodeIfNeeded();
            } catch (ConnectionException $e) {
                throw new ConnectionException('Not connected. ' . $e->getMessage(), 0, $e);
            }
        }
    }