Check if connection is alive every reconnect_timeout seconds.
545491
def _check_connection(self):
        """"""
        if ((self.tcp_disconnect_timer + 2 * self.reconnect_timeout) <
                time.time()):
            self.tcp_disconnect_timer = time.time()
            raise OSError('No response from {}. Disconnecting'.format(
                self.server_address))
        if (self.tcp_check_timer + self.reconnect_timeout) >= time.time():
            return
        msg = Message().modify(
            child_id=255, type=self.const.MessageType.internal,
            sub_type=self.const.Internal.I_VERSION)
        self.add_job(msg.encode)
        self.tcp_check_timer = time.time()
933232
public static void detectDeadConnections() {
        if (CONNECTION_DETECTOR_RUNNING) {
            return;
        }
        final Logger log = LoggerFactory.getLogger(ConnectionManager.class);
        Thread deadConnThread = new Thread(new Runnable() {
            public void run() {
                CONNECTION_DETECTOR_RUNNING = true;
                try {
                    log.debug("Starting dead connection detection thread");
                    while (detectDeadConnection) {
                        log.debug("Checking if there are any dead connections");
                        long now = DateTime.now().getMillis();
                        for (DataSiftConnection data : connections) {
                            if (data.lastSeen() != null) {
                                if (now - data.lastSeen().getMillis() >=
                                        TimeUnit.SECONDS.toMillis(CONNECTION_TIMEOUT_LIMIT)) {
                                    log.info("Dead connection found, triggering re-connection");
                                    data.closeAndReconnect();
                                }
                            }
                        }
                        log.debug(String.format("Checked %s connections", connections.size()));
                        try {
                            Thread.sleep(TimeUnit.SECONDS.toMillis(CONNECTION_TIMEOUT));
                        } catch (InterruptedException e) {
                            LoggerFactory.getLogger(getClass()).info("Interrupted while waiting to check conn");
                        }
                    }
                } finally {
                    CONNECTION_DETECTOR_RUNNING = false;
                }
            }
        }, "dead-connections-monitor");
        deadConnThread.setDaemon(true);
        deadConnThread.start();
    }
971199
def check_connections(self):
        ''''''
        logger.info('Checking connections')
        if self._lookupd:
            self.discover(self._topic)

        # Make sure we're connected to all the prescribed hosts
        for hostspec in self._nsqd_tcp_addresses:
            logger.debug('Checking nsqd instance %s', hostspec)
            host, port = hostspec.split(':')
            port = int(port)
            conn = self._connections.get((host, port), None)
            # If there is no connection to it, we have to try to connect
            if not conn:
                logger.info('Connecting to %s:%s', host, port)
                self.connect(host, port)
            elif not conn.alive():
                # If we've connected to it before, but it's no longer alive,
                # we'll have to make a decision about when to try to reconnect
                # to it, if we need to reconnect to it at all
                if conn.ready_to_reconnect():
                    logger.info('Reconnecting to %s:%s', host, port)
                    if conn.connect():
                        conn.setblocking(0)
                        self.reconnected(conn)
            else:
                logger.debug('Checking freshness')
                now = time.time()
                time_check = math.ceil(now - self.last_recv_timestamp)
                if time_check >= ((self.heartbeat_interval * 2) / 1000.0):
                    if conn.ready_to_reconnect():
                        logger.info('Reconnecting to %s:%s', host, port)
                        if conn.connect():
                            conn.setblocking(0)
                            self.reconnected(conn)
351363
public boolean isConnectionStale() {
        if (lastUsedTime == 0)
            return false;

        long currentTime = System.currentTimeMillis();
        long timeSinceLastUse = currentTime - lastUsedTime;
        return (timeSinceLastUse > MAX_KEEPALIVE);
    }
873442
def _check(self):
        ''''''
        _logger.debug('Check if timeout.')
        self._call_later_handle = None

        if self._touch_time is not None:
            difference = self._event_loop.time() - self._touch_time
            _logger.debug('Time difference %s', difference)

            if difference > self._timeout:
                self._connection.close()
                self._timed_out = True

        if not self._connection.closed():
            self._schedule()
1026108
def until_connected(self, timeout=None):
        """"""
        t0 = self.ioloop.time()
        yield self.until_running(timeout=timeout)
        t1 = self.ioloop.time()
        if timeout:
            timedelta = timeout - (t1 - t0)
        else:
            timedelta = None
        assert get_thread_ident() == self.ioloop_thread_id
        yield self._connected.until_set(timeout=timedelta)
928420
function checkStatus() {
    flushMonitoringOperations(self.queue);

    if (self.queue.length === 0) {
      // Get all the known connections
      var connections = self.availableConnections.concat(self.inUseConnections);

      // Check if we have any in flight operations
      for (var i = 0; i < connections.length; i++) {
        // There is an operation still in flight, reschedule a
        // check waiting for it to drain
        if (connections[i].workItems.length > 0) {
          return setTimeout(checkStatus, 1);
        }
      }

      destroy(self, connections, { force: false }, callback);
      // } else if (self.queue.length > 0 && !this.reconnectId) {
    } else {
      // Ensure we empty the queue
      _execute(self)();
      // Set timeout
      setTimeout(checkStatus, 1);
    }
  }
554486
function checkConnection(){

    return new Promise(function(resolve, reject){

        // 1.5s connection timeout
        const watchdog = setTimeout(function(){
            // throw error
            reject(new Error('Timeout, no response detected - is NodeMCU online and the Lua interpreter ready ?'));
        }, 1500);

        // send a simple print command to the lua engine
        _virtualTerminal.executeCommand(_luaCommandBuilder.command.echo)
            .then(({echo, response}) => {
                // clear watchdog
                clearTimeout(watchdog);

                // validate command echo and command output
                if (response == 'echo1337' && echo == 'print("echo1337")') {
                    resolve();
                } else {
                    _logger.log('Echo:', echo);
                    _logger.debug('Response:', response);
                    reject(new Error('No response detected - is NodeMCU online and the Lua interpreter ready ?'));
                }
            })
            .catch(reject)
    });

}
758374
def is_connected(self):
        
        if self._client is not None:
            try:
                self._client.server_info()
            except ConnectionFailure:
                return False
            return True
        else:
            return False
1230034
private static boolean waitForServerDown(int port, long timeout) {
    long start = System.currentTimeMillis();
    while (true) {
      try {
        Socket sock = new Socket("localhost", port);
        try {
          OutputStream outstream = sock.getOutputStream();
          outstream.write("stat".getBytes());
          outstream.flush();
        } finally {
          sock.close();
        }
      } catch (IOException e) {
        return true;
      }

      if (System.currentTimeMillis() > start + timeout) {
        break;
      }
      try {
        Thread.sleep(250);
      } catch (InterruptedException e) {
        // ignore
      }
    }
    return false;
  }
729110
def check_connection (self):
        
        self.url_connection = telnetlib.Telnet(timeout=self.aggregate.config["timeout"])
        if log.is_debug(LOG_CHECK):
            self.url_connection.set_debuglevel(1)
        self.url_connection.open(self.host, self.port)
        if self.user:
            self.url_connection.read_until("login: ", 10)
            self.url_connection.write(encode(self.user)+"\n")
            if self.password:
                self.url_connection.read_until("Password: ", 10)
                self.url_connection.write(encode(self.password)+"\n")
                # XXX how to tell if we are logged in??
        self.url_connection.write("exit\n")
647608
def is_connected(self):
        """"""
        try:
            self._conn.noop()
        except (AttributeError, smtplib.SMTPServerDisconnected):
            return False
        else:
            return True
678177
private boolean checkConnection() {
		if (connection == null) {
			if (System.currentTimeMillis() >= reconnectTimestamp) {
				long start = System.currentTimeMillis();
				try {
					connection = connect(url, user, password);
					statement = connection.prepareStatement(sql);
					InternalLogger.log(Level.ERROR, "Lost log entries due to broken database connection: " + lostCount);
					lostCount = 0;
					return true;
				} catch (NamingException ex) {
					long now = System.currentTimeMillis();
					reconnectTimestamp = now + Math.max(MIN_RETRY_INTERVAL, (now - start) * 2);
					closeConnectionSilently();
					return false;
				} catch (SQLException ex) {
					long now = System.currentTimeMillis();
					reconnectTimestamp = now + Math.max(MIN_RETRY_INTERVAL, (now - start) * 2);
					closeConnectionSilently();
					return false;
				}
			} else {
				return false;
			}
		} else {
			return true;
		}
	}
1260148
def checkTimeout(self, now):
        """"""
        log.debug("checking for timeout on session %s", self)
        if now - self.last_update > self.timeout:
            raise TftpTimeout("Timeout waiting for traffic")
1163917
def timeout(self, timeout):
        '''
        '''
        if self._timeout is None:
            self.event('connection_made').bind(self._add_timeout)
            self.event('connection_lost').bind(self._cancel_timeout)
        self._timeout = timeout or 0
        self._add_timeout(None)
670336
function _check_timeout($fp)
    {
        if ($this->read_timeout > 0) {
            $fp_status = socket_get_status($fp);
            if ($fp_status["timed_out"]) {
                $this->timed_out = true;
                return true;
            }
        }
        return false;
    }
194716
def await_connection(host, port):
    """"""
    for i in range(CONNECT_ATTEMPTS):
        try:
            conn = socket.create_connection((host, port), CONNECT_TIMEOUT)
            conn.close()
            return True
        except (IOError, socket.error):
            time.sleep(1)
    return False