Send a heartbeat if needed. Tracks last heartbeat send time.
432229
def send_heartbeat(self):
        '''
        
        '''
        # Note that this does not take into account the time that we last
        # sent a frame. Hearbeats are so small the effect should be quite
        # limited. Also note that we're looking for something near to our
        # scheduled interval, because if this is exact, then we'll likely
        # actually send a heartbeat at twice the period, which could cause
        # a broker to kill the connection if the period is large enough. The
        # 90% bound is arbitrary but seems a sensible enough default.
        if self.connection._heartbeat:
            if time.time() >= (self._last_heartbeat_send + 0.9 *
                               self.connection._heartbeat):
                self.send_frame(HeartbeatFrame(self.channel_id))
                self._last_heartbeat_send = time.time()
621316
def on_heartbeat(self, message):
        

        logger.info("Got a heartbeat")
        logger.info("Heartbeat message: {}".format(message))
        self.heartbeat_thread.update_sequence(message['d'])
        return
1174768
def set_heartbeat(self, state):
        

        if state in ["on", "off", "open"]:
            self.heartbeat = state
            self.server.request("screen_set %s heartbeat %s" % (self.ref, self.heartbeat))
405692
def scheduleNextHeartbeat(self, nextRun):
        
        import threading
        from datetime import datetime
        tilNextTime = max(nextRun - datetime.utcnow().timestamp(), 0)
        logging.getLogger('recorder').info("Scheduling next ping in " + str(round(tilNextTime, 3)) + " seconds")
        threading.Timer(tilNextTime, self.ping).start()
374079
private void updateHeartbeatTime(MemberState member, Throwable error) {
    if (heartbeatFuture == null) {
      return;
    }

    if (error != null && member.getHeartbeatStartTime() == heartbeatTime) {
      int votingMemberSize = context.getClusterState().getActiveMemberStates().size() + (context.getCluster().member().type() == Member.Type.ACTIVE ? 1 : 0);
      int quorumSize = (int) Math.floor(votingMemberSize / 2) + 1;
      // If a quorum of successful responses cannot be achieved, fail this heartbeat. Ensure that only
      // ACTIVE members are considered. A member could have been transitioned to another state while the
      // heartbeat was being sent.
      if (member.getMember().type() == Member.Type.ACTIVE && ++heartbeatFailures > votingMemberSize - quorumSize) {
        heartbeatFuture.completeExceptionally(new InternalException("Failed to reach consensus"));
        completeHeartbeat();
      }
    } else {
      member.setHeartbeatTime(System.currentTimeMillis());

      // Sort the list of commit times. Use the quorum index to get the last time the majority of the cluster
      // was contacted. If the current heartbeatFuture's time is less than the commit time then trigger the
      // commit future and reset it to the next commit future.
      if (heartbeatTime <= heartbeatTime()) {
        heartbeatFuture.complete(null);
        completeHeartbeat();
      }
    }
  }
550682
function sendHeartbeat() {
    _.forOwn(_this.socks, function (sock) {
      sock.write('hb');
    });
    setTimeout(sendHeartbeat, _this.heartbeatFreq);
  }
732583
public function heartbeat($task)
    {
        $current = time();
        if ($current - $this->_last_heartbeat >= $this->_heartbeat_interval) {
            $this->_last_heartbeat = $current;
            if ($redis = $this->_getRedis()) {
                $redis->hSet($this->getTaskMetaKey($task), self::FIELD_HEARTBEAT_TIME, date('c', $current));
            }
        }
    }
1248820
private void notifyHeartbeat() {
    ArrayList<NGHeartbeatListener> listeners;
    synchronized (heartbeatListeners) {
      if (heartbeatListeners.isEmpty()) {
        return;
      }
      // copy collection to avoid executing callbacks under lock
      listeners = new ArrayList<>(heartbeatListeners);
    }

    for (NGHeartbeatListener listener : listeners) {
      listener.heartbeatReceived();
    }
  }
1170493
def heartbeat_tick(self, rate=2):
        
        if not self.heartbeat:
            return

        # treat actual data exchange in either direction as a heartbeat
        sent_now = self.method_writer.bytes_sent
        recv_now = self.method_reader.bytes_recv
        if self.prev_sent is None or self.prev_sent != sent_now:
            self.last_heartbeat_sent = monotonic()
        if self.prev_recv is None or self.prev_recv != recv_now:
            self.last_heartbeat_received = monotonic()
        self.prev_sent, self.prev_recv = sent_now, recv_now

        # send a heartbeat if it's time to do so
        if monotonic() > self.last_heartbeat_sent + self.heartbeat:
            self.send_heartbeat()
            self.last_heartbeat_sent = monotonic()

        # if we've missed two intervals' heartbeats, fail; this gives the
        # server enough time to send heartbeats a little late
        if (self.last_heartbeat_received and
                self.last_heartbeat_received + 2 *
                self.heartbeat < monotonic()):
            raise ConnectionForced('Too many heartbeats missed')
164081
private Future<?> startHeartbeat(final WebSocket websocket, final int heartbeatInterval) {
        // first heartbeat should assume last heartbeat was answered properly
        heartbeatAckReceived.set(true);
        return api.getThreadPool().getScheduler().scheduleWithFixedDelay(() -> {
            try {
                if (heartbeatAckReceived.getAndSet(false)) {
                    sendHeartbeat(websocket);
                    logger.debug("Sent heartbeat (interval: {})", heartbeatInterval);
                } else {
                    websocket.sendClose(WebSocketCloseReason.HEARTBEAT_NOT_PROPERLY_ANSWERED.getNumericCloseCode(),
                                        WebSocketCloseReason.HEARTBEAT_NOT_PROPERLY_ANSWERED.getCloseReason());
                }
            } catch (Throwable t) {
                logger.error("Failed to send heartbeat or close web socket!", t);
            }
        }, 0, heartbeatInterval, TimeUnit.MILLISECONDS);
    }
1217289
def heartbeat(self):
        

        self.thread_debug("heartbeat")

        # check stats -- should be incrementing
        if self.last_stats:
            if self.stats.http_run <= self.last_stats.http_run:
                self.NOTIFY("No monitors run since last heartbeat!", service="heartbeat")
                return
            elif self.stats.http_handled <= self.last_stats.http_handled:
                self.NOTIFY("No monitor results handled since last heartbeat!", service="heartbeat")
                return

        # ping heartbeat as a webhook
        if self.config.get('heartbeat-hook'):
            result = requests.get(self.config.get('heartbeat-hook'))
            if result.status_code != 200:
                self.NOTIFY("Heartbeat ping to statuscake failed!", level="ERROR")

        # keep a static copy of the last run stats
        self.last_stats = self.stats.copy()
1139481
def send_heartbeat
      millis = Time.now.strftime('%s%L').to_i
      @bot.debug("Sending voice heartbeat at #{millis}")

      @client.send({
        op: 3,
        d: nil
      }.to_json)
    end
628270
private void checkHeartbeatTimeout(PropertyKey intervalKey, PropertyKey timeoutKey) {
    long interval = getMs(intervalKey);
    long timeout = getMs(timeoutKey);
    Preconditions.checkState(interval < timeout,
        "heartbeat interval (%s=%s) must be less than heartbeat timeout (%s=%s)", intervalKey,
        interval, timeoutKey, timeout);
  }
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();
            }
        }
    }
829368
public function lastHeartbeat()
    {
        $check = Cache::get($this->HEARTBEAT_WORKER_KEY);
        if (empty($check)) {
            return 'never';
        }

        return date(Library\Utils\Constants::COMMON_DATETIME.' T', $check);
    }
358630
private void setHeartbeatInterval(long heartbeatInterval,
                                    long heartbeatRecheckInterval) {
    this.heartbeatInterval = heartbeatInterval;
    this.heartbeatRecheckInterval = heartbeatRecheckInterval;
    this.heartbeatExpireInterval = 2 * heartbeatRecheckInterval +
      10 * heartbeatInterval;
    ReplicationConfigKeys.blockInvalidateLimit =
      Math.max(ReplicationConfigKeys.blockInvalidateLimit,
               20 * (int) (heartbeatInterval/1000L));
    
  }
517174
def send(self, ws, seq):
        

        payload = {'op': 1, 'd': seq}
        payload = json.dumps(payload)
        logger.debug("Sending heartbeat with payload {}".format(payload))
        ws.send(payload)
        return