Send heartbeats and calculate clock drift. This method is expected to be called periodically because it calculates
the clock drift based on the expected and actual invocation period.
543127
void heartbeat() {
        if (!clusterService.isJoined()) {
            return;
        }

        checkClockDrift(heartbeatIntervalMillis);

        final long clusterTime = clusterClock.getClusterTime();
        if (clusterService.isMaster()) {
            heartbeatWhenMaster(clusterTime);
        } else {
            heartbeatWhenSlave(clusterTime);
        }
    }
190980
public function check_heartbeat()
    {
        if (!$this->sock->connected)
        {
            $this->reconnect();
            return;
        }
        // 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->reconnect();
            }

            // time for client to send a heartbeat
            if (($this->heartbeat / 2) < $t_write) {
                $this->write_heartbeat();
            }
        }
    }
1113789
public void acknowledgeHeartBeat( Instance scopedInstance ) {

		String count = scopedInstance.data.get( MISSED_HEARTBEATS );
		if( count != null
				&& Integer.parseInt( count ) > THRESHOLD )
			this.logger.info( "Agent " + InstanceHelpers.computeInstancePath( scopedInstance ) + " is alive and reachable again." );

		// Store the moment the first ACK (without interruption) was received.
		// If we were deploying, store it.
		// If we were in problem, store it.
		// If we were already deployed and started, do NOT override it.
		if( scopedInstance.getStatus() != InstanceStatus.DEPLOYED_STARTED
				|| ! scopedInstance.data.containsKey( Instance.RUNNING_FROM ))
			scopedInstance.data.put( Instance.RUNNING_FROM, String.valueOf( new Date().getTime()));

		scopedInstance.setStatus( InstanceStatus.DEPLOYED_STARTED );
		scopedInstance.data.remove( MISSED_HEARTBEATS );
	}
187006
public void setHeartbeatTime(int newHeartbeatTime) {
		if (newHeartbeatTime > 0) {
			if (newHeartbeatTime > heartbeatMaxTime
					|| newHeartbeatTime < heartbeatMinTime) {
				raiseOrtcEvent(EventEnum.OnException, this, new Exception(
						"Heartbeat time is out of limits - Min: "
								+ heartbeatMinTime + " | Max: "
								+ heartbeatMaxTime));
			} else {
				heartbeatTime = newHeartbeatTime;
			}
		} else {
			raiseOrtcEvent(EventEnum.OnException, this, new Exception(
					"Invalid heartbeat time " + newHeartbeatTime));
		}
	}
924202
def start_heartbeat(self):
        """"""
        self.stop_heartbeat()

        self._heartbeat_timer = periodic.Callback(self._heartbeat,
                                                  self._heartbeat_interval,
                                                  self.server.io_loop)
        self._heartbeat_timer.start()
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))
1205183
public void tick() throws InterruptedException {
    if (mPreviousTickMs != 0) {
      long executionTimeMs = mClock.millis() - mPreviousTickMs;
      if (executionTimeMs > mIntervalMs) {
        mLogger.warn("{} last execution took {} ms. Longer than the interval {}", mThreadName,
            executionTimeMs, mIntervalMs);
      } else {
        mSleeper.sleep(Duration.ofMillis(mIntervalMs - executionTimeMs));
      }
    }
    mPreviousTickMs = mClock.millis();
  }
1242243
private CompletableFuture<HeartbeatResponse> handleHeartbeat(HeartbeatRequest request) {
    log.trace("Received {}", request);
    boolean newLeader = !Objects.equals(selectorManager.leader(), request.leader());
    selectorManager.resetAll(request.leader(), request.members());
    HeartbeatResponse response = HeartbeatResponse.builder()
        .withStatus(RaftResponse.Status.OK)
        .build();
    if (newLeader) {
      resetAllIndexes();
    }
    log.trace("Sending {}", response);
    return CompletableFuture.completedFuture(response);
  }
478064
public void tick() {
        final long count = uncounted.sumThenReset();
        final double instantRate = count / interval;
        if (initialized) {
            rate += (alpha * (instantRate - rate));
        } else {
            rate = instantRate;
            initialized = true;
        }
    }
587642
private void sendHeartbeat(WebSocket websocket) {
        ObjectNode heartbeatPacket = JsonNodeFactory.instance.objectNode();
        heartbeatPacket.put("op", GatewayOpcode.HEARTBEAT.getCode());
        heartbeatPacket.put("d", lastSeq);
        WebSocketFrame heartbeatFrame = WebSocketFrame.createTextFrame(heartbeatPacket.toString());
        nextHeartbeatFrame.set(heartbeatFrame);
        websocket.sendFrame(heartbeatFrame);
    }
1058926
private void updateLocalityWaitTimes(long currentTime) {
    long timeSinceLastHeartbeat =
      (lastHeartbeatTime == 0 ? 0 : currentTime - lastHeartbeatTime);
    lastHeartbeatTime = currentTime;
    for (JobInfo info: infos.values()) {
      if (info.skippedAtLastHeartbeat) {
        info.timeWaitedForLocalMap += timeSinceLastHeartbeat;
        // We reset the flag so that timeWaitedForLocalMap is increment only
        // once. It will be increment again if skippedAtLastHeartbeat is set
        // to true next time.
        info.skippedAtLastHeartbeat = false;
      }
    }
  }
254012
protected void tick ()
    {
        // if we're not connected, skip it
        if (_comm == null) {
            return;
        }

        long now = RunAnywhere.currentTimeMillis();
        if (_dcalc != null) {
            // if our current calculator is done, clear it out
            if (_dcalc.isDone()) {
                if (debugLogMessages()) {
                    log.info("Time offset from server: " + _serverDelta + "ms.");
                }
                _dcalc = null;
            } else if (_dcalc.shouldSendPing()) {
                // otherwise, send another ping
                PingRequest req = new PingRequest();
                _comm.postMessage(req);
                _dcalc.sentPing(req);
            }

        } else if (now - _comm.getLastWrite() > PingRequest.PING_INTERVAL) {
            // if we haven't sent anything over the network in a while, we ping the server to let
            // it know that we're still alive
            _comm.postMessage(new PingRequest());

        } else if (now - _lastSync > CLOCK_SYNC_INTERVAL) {
            // resync our clock with the server
            establishClockDelta(now);
        }
    }
560893
public function onFinish()
    {
        $this->appInstance->unsubscribe('s2c:' . $this->sessId, [$this, 's2c']);
        $this->appInstance->unsubscribe('w8in:' . $this->sessId, [$this, 'w8in']);
        Timer::remove($this->heartbeatTimer);
        if ($this->heartbeatOnFinish) {
            $this->sendFrame('h');
        }
        parent::onFinish();
    }
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')
750374
async def post_heartbeat(self, msg, _context):
        """"""

        name = msg.get('name')

        await self.service_manager.send_heartbeat(name)
696010
@Override
  public void heartbeat() {
    // Prepare metadata for the next heartbeat
    BlockHeartbeatReport blockReport = mBlockWorker.getReport();
    BlockStoreMeta storeMeta = mBlockWorker.getStoreMeta();

    // Send the heartbeat and execute the response
    Command cmdFromMaster = null;
    List<alluxio.grpc.Metric> metrics = new ArrayList<>();
    for (Metric metric : MetricsSystem.allWorkerMetrics()) {
      metrics.add(metric.toProto());
    }
    try {
      cmdFromMaster = mMasterClient.heartbeat(mWorkerId.get(), storeMeta.getCapacityBytesOnTiers(),
          storeMeta.getUsedBytesOnTiers(), blockReport.getRemovedBlocks(),
          blockReport.getAddedBlocks(), blockReport.getLostStorage(), metrics);
      handleMasterCommand(cmdFromMaster);
      mLastSuccessfulHeartbeatMs = System.currentTimeMillis();
    } catch (IOException | ConnectionFailedException e) {
      // An error occurred, log and ignore it or error if heartbeat timeout is reached
      if (cmdFromMaster == null) {
        LOG.error("Failed to receive master heartbeat command.", e);
      } else {
        LOG.error("Failed to receive or execute master heartbeat command: {}",
            cmdFromMaster.toString(), e);
      }
      mMasterClient.disconnect();
      if (mHeartbeatTimeoutMs > 0) {
        if (System.currentTimeMillis() - mLastSuccessfulHeartbeatMs >= mHeartbeatTimeoutMs) {
          if (ServerConfiguration.getBoolean(PropertyKey.TEST_MODE)) {
            throw new RuntimeException("Master heartbeat timeout exceeded: " + mHeartbeatTimeoutMs);
          }
          // TODO(andrew): Propagate the exception to the main thread and exit there.
          ProcessUtils.fatalError(LOG, "Master heartbeat timeout exceeded: %d",
              mHeartbeatTimeoutMs);
        }
      }
    }
  }
928850
def Heartbeat(self):
    
    heartbeat_msg = common_pb2.Message(
        message_type="Heartbeat",
        destination=common_pb2.Address(service_name="system"))
    self._SendImpl(heartbeat_msg)