check supervisor's heartBeat,

@return
484737
public boolean checkHeartBeat() {

        String dataPath = executorMeta.getLocalDir();
        File localstate = new File(dataPath + "/data/" + startType + "/" + startType + ".heartbeat/");
        Long modefyTime = localstate.lastModified();

        if (System.currentTimeMillis() - modefyTime > JOYConstants.EXECUTOR_HEARTBEAT_TIMEOUT) {

            LOG.info("----------------------");
            modefyTime = localstate.lastModified();
            LOG.info(modefyTime.toString());

            LOG.info(Long.toString(new Date().getTime()));
            LOG.info(dataPath + "/data/" + startType + "/" + startType + ".heartbeat/");

            LOG.info("can't get heartbeat over " + String.valueOf(JOYConstants.EXECUTOR_HEARTBEAT_TIMEOUT) + " seconds");
            return false;
        } else
            return true;
    }
765187
private boolean checkTickerFreshness() {
		final QuoteManager quoteManager = bitfinexApiBroker.getQuoteManager();
		final Map<BitfinexStreamSymbol, Long> heartbeatValues = quoteManager.getLastTickerActivity();

		return checkTickerFreshness(heartbeatValues);
	}
86667
private int determineHeartbeatInterval(Map properties)
    {
        // How often should we heartbeat?
        int heartbeatInterval = JFapChannelConstants.DEFAULT_HEARTBEAT_INTERVAL;
        try
        {
            heartbeatInterval = Integer.parseInt(RuntimeInfo.getProperty(JFapChannelConstants.RUNTIMEINFO_KEY_HEARTBEAT_INTERVAL, "" + heartbeatInterval));
        } catch (NumberFormatException nfe)
        {
            // No FFDC code needed
        }

        if (properties != null)
        {
            String intervalStr = (String) properties.get(JFapChannelConstants.CHANNEL_CONFIG_HEARTBEAT_INTERVAL_PROPERTY);
            if (intervalStr != null)
            {
                try
                {
                    heartbeatInterval = Integer.parseInt(intervalStr);
                } catch (NumberFormatException nfe)
                {
                    // No FFDC code needed
                }
            }
        }
        return heartbeatInterval;
    }
529421
public ClientSocket openIfHeartbeatActive()
  {
    if (_state.isClosed()) {
      return null;
    }
    
    if (! _isHeartbeatActive && _isHeartbeatServer) {
      return null;
    }

    ClientSocket stream = openRecycle();

    if (stream != null)
      return stream;

    return connect();
  }
755853
function monitorServer(server) {
  // executes a single check of a server
  const checkServer = callback => {
    let start = process.hrtime();

    // emit a signal indicating we have started the heartbeat
    server.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(server.name));

    server.command(
      'admin.$cmd',
      { ismaster: true },
      {
        monitoring: true,
        socketTimeout: server.s.options.connectionTimeout || 2000
      },
      function(err, result) {
        let duration = calculateDurationInMs(start);

        if (err) {
          server.emit(
            'serverHeartbeatFailed',
            new ServerHeartbeatFailedEvent(duration, err, server.name)
          );

          return callback(err, null);
        }

        const isMaster = result.result;
        server.emit(
          'serverHeartbeatSucceded',
          new ServerHeartbeatSucceededEvent(duration, isMaster, server.name)
        );

        return callback(null, isMaster);
      }
    );
  };

  const successHandler = isMaster => {
    server.s.monitoring = false;

    // emit an event indicating that our description has changed
    server.emit('descriptionReceived', new ServerDescription(server.description.address, isMaster));

    // schedule the next monitoring process
    server.s.monitorId = setTimeout(
      () => monitorServer(server),
      server.s.options.heartbeatFrequencyMS
    );
  };

  // run the actual monitoring loop
  server.s.monitoring = true;
  checkServer((err, isMaster) => {
    if (!err) {
      successHandler(isMaster);
      return;
    }

    // According to the SDAM specification's "Network error during server check" section, if
    // an ismaster call fails we reset the server's pool. If a server was once connected,
    // change its type to `Unknown` only after retrying once.

    // TODO: we need to reset the pool here

    return checkServer((err, isMaster) => {
      if (err) {
        server.s.monitoring = false;

        // revert to `Unknown` by emitting a default description with no isMaster
        server.emit('descriptionReceived', new ServerDescription(server.description.address));

        // do not reschedule monitoring in this case
        return;
      }

      successHandler(isMaster);
    });
  });
}
1221636
def Heartbeat(self):
    """"""
    service_key = _GetServiceKey()
    try:
      winreg.SetValueEx(service_key, "Nanny.heartbeat", 0, winreg.REG_DWORD,
                        int(time.time()))
    except OSError as e:
      logging.debug("Failed to heartbeat nanny at %s: %s", service_key, e)
1071469
@Override
    protected void checkIfHeartbeatSkipped(String name, EventChannelStruct eventChannelStruct) {
            // Check if heartbeat have been skipped, can happen if
            // 1- the notifd is dead (if not ZMQ)
            // 2- the server is dead
            // 3- The network was down;
            // 4- The server has been restarted on another host.
//        long now = System.currentTimeMillis();
//        boolean heartbeat_skipped =
//                ((now - eventChannelStruct.last_heartbeat) > KeepAliveThread.getHeartBeatPeriod());
        if (KeepAliveThread.heartbeatHasBeenSkipped(eventChannelStruct) ||
            eventChannelStruct.heartbeat_skipped || eventChannelStruct.notifd_failed) {

            eventChannelStruct.heartbeat_skipped = true;

            // Check notifd by trying to read an attribute of the event channel
            DevError dev_error = null;
            try {
                eventChannelStruct.eventChannel.MyFactory();

                //	Check if DS is now running on another host
                if (checkIfHostHasChanged(eventChannelStruct))
                    eventChannelStruct.notifd_failed = true;
            } catch (RuntimeException e1) {
                //	MyFactory has failed
                dev_error = new DevError();
                dev_error.severity = ErrSeverity.ERR;
                dev_error.origin = "NotifdEventConsumer.checkIfHeartbeatSkipped()";
                dev_error.reason = "API_EventException";
                dev_error.desc = "Connection failed with notify daemon";

                //	Try to add reason
                int pos = e1.toString().indexOf(":");
                if (pos > 0) dev_error.desc += "  (" + e1.toString().substring(0, pos) + ")";

                eventChannelStruct.notifd_failed = true;

                //	reset the event import info stored in DeviceProxy object
                //	Until today, this feature is used only by Astor (import with external info).
                try {
                    DeviceProxyFactory.get(name,
                            eventChannelStruct.dbase.getUrl().getTangoHost()).set_evt_import_info(null);
                } catch (DevFailed e) {
                    System.err.println("API received a DevFailed :	" + e.errors[0].desc);
                }
            }

            //	Force to reconnect if not using database
            if (!eventChannelStruct.use_db)
                eventChannelStruct.notifd_failed = true;

            //	Check if has_notifd_closed_the_connection many times (nework blank)
            if (!eventChannelStruct.notifd_failed &&
                    eventChannelStruct.has_notifd_closed_the_connection >= 3)
                eventChannelStruct.notifd_failed = true;

            //	If notifd_failed  --> try to reconnect
            if (eventChannelStruct.notifd_failed) {
                eventChannelStruct.notifd_failed = !reconnect_to_channel(name);
                if (!eventChannelStruct.notifd_failed)
                    reconnect_to_event(name);
            }

            Enumeration callback_structs = EventConsumer.getEventCallbackMap().elements();
            while (callback_structs.hasMoreElements()) {
                EventCallBackStruct callback_struct = (EventCallBackStruct) callback_structs.nextElement();
                if (callback_struct.channel_name.equals(name)) {
                    //	Push exception
                    if (dev_error != null)
                        pushReceivedException(eventChannelStruct, callback_struct, dev_error);
                    else
                        pushServerNotRespondingException(eventChannelStruct, callback_struct);

                    //	If reconnection done, try to re subscribe
                    //		and read attribute in synchronous mode
                    if (!callback_struct.event_name.equals(eventNames[DATA_READY_EVENT]))
                        if (!eventChannelStruct.notifd_failed)
                            if (eventChannelStruct.consumer.reSubscribe(eventChannelStruct, callback_struct))
                                readAttributeAndPush(eventChannelStruct, callback_struct);
                }
            }
        }// end if heartbeat_skipped
        else
            eventChannelStruct.has_notifd_closed_the_connection = 0;
    }
119470
def _get_monitoring_heartbeat(self):
        
        target = self.uri + '/monitoring/heartbeat'
        response = self.session.get(target)
        return response
657785
boolean onHeartbeatStop()
  {
    SocketPool clusterSocketPool;
    
    if (isExternal()) {
      clusterSocketPool = _clusterSocketPool.getAndSet(null);
    }
    else {
      clusterSocketPool = _clusterSocketPool.get();
    }

    if (clusterSocketPool != null) {
      clusterSocketPool.getFactory().notifyHeartbeatStop();
    }

    /*
    if (! _heartbeatState.notifyHeartbeatStop()) {
      return false;
    }
    */
    
    log.fine("notify-heartbeat-stop " + this);

    return true;
  }
1212216
@Override
  synchronized boolean processHeartbeat(TaskTrackerStatus trackerStatus,
      boolean initialContact) {
    boolean loggingEnabled = LOG.isDebugEnabled();
    String trackerName = trackerStatus.getTrackerName();
    boolean seenBefore = updateTaskTrackerStatus(trackerName, trackerStatus);
    TaskTracker taskTracker = getTaskTracker(trackerName);
    // update the status of the task tracker. Also updates all aggregate
    // statistics
    if (loggingEnabled) {
      LOG.debug("processing heartbeat for " + trackerName);
      LOG.debug("updating TaskTracker status for " + trackerName);
    }
    if (initialContact) {
      // If it's first contact, then clear out 
      // any state hanging around
      if (seenBefore) {
        lostTaskTracker(taskTracker);
      }
    } else {
      // If not first contact, there should be some record of the tracker
      if (!seenBefore) {
        LOG.warn("Status from unknown Tracker : " + trackerName);
        updateTaskTrackerStatus(trackerName, null);
        return false;
      }
    }

    if (initialContact) {
      if (loggingEnabled) {
        LOG.debug("adding new tracker name = " + trackerName);
      }
      addNewTracker(taskTracker);
    }

    if (loggingEnabled) {
      LOG.debug("updating TaskStatus for " + trackerName);
    }
    // update status of all tasks from heartbeat
    updateTaskStatuses(trackerStatus);

    return true;
  }
1157866
synchronized int checkState() {
    if (this.state == Job.RUNNING) {
      checkRunningState();
    }
    if (this.state != Job.WAITING) {
      return this.state;
    }
    if (this.dependingJobs == null || this.dependingJobs.size() == 0) {
      this.state = Job.READY;
      return this.state;
    }
    Job pred = null;
    int n = this.dependingJobs.size();
    for (int i = 0; i < n; i++) {
      pred = this.dependingJobs.get(i);
      int s = pred.checkState();
      if (s == Job.WAITING || s == Job.READY || s == Job.RUNNING) {
        break; // a pred is still not completed, continue in WAITING
        // state
      }
      if (s == Job.FAILED || s == Job.DEPENDENT_FAILED) {
        this.state = Job.DEPENDENT_FAILED;
        this.message = "depending job " + i + " with jobID "
          + pred.getJobID() + " failed. " + pred.getMessage();
        break;
      }
      // pred must be in success state
      if (i == n - 1) {
        this.state = Job.READY;
      }
    }

    return this.state;
  }
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);
                        }
                    }
                }
            }
        }
    }
333384
static boolean heartbeatHasBeenSkipped(EventChannelStruct eventChannelStruct) {
        long now = System.currentTimeMillis();
        //System.out.println(now + "-" + eventChannelStruct.last_heartbeat + "=" +
        //        (now - eventChannelStruct.last_heartbeat));
        return ((now - eventChannelStruct.last_heartbeat) > EVENT_HEARTBEAT_PERIOD);
    }
750374
async def post_heartbeat(self, msg, _context):
        """"""

        name = msg.get('name')

        await self.service_manager.send_heartbeat(name)
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);
  }
1062305
public boolean checkCondition() {

        // assure that the checkinterval is elapsed .....
        if (super.checkCondition()) {
            return true;
        }

        if (this.watchdogReference.isStale()) {
            return false;
        }

        Watchdog wd = this.watchdogReference.getWatchdog();

        //log.info("Checking "+this+"\n watched WD is alive="+watchedWatchdog.isAlive()+" is killed="+watchedWatchdog.isKilled()+" WD-Thead="+this.watchedWatchdog.getThreadHandle());
        if (!wd.isAlive()) {
            if (log.isInfoEnabled()) {
                String logString = "RestartCondition :: Watchdog " + wd.getThreadHandle() + " is not alive ";
                log.info(new CheckConditionFailedLog(this, logString).toString());
            }
            return false;
        }
        return true;
    }
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')