starts the emission of heartbeats at regular intervals
553543
function startHeartbeats () {
    _isMaster = true
    if (_hearbeatInterval) return
    debug('starting heartbeats')
    _sendHeartbeat()
    _hearbeatInterval = setInterval(_sendHeartbeat, HEARTBEAT_INTERVAL)
  }
859217
public void run() {

        while (!stop) {
            long t0 = System.currentTimeMillis();

            try {
                EventConsumer.subscribeIfNotDone();
                resubscribe_if_needed();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            catch (Error err) {
                err.printStackTrace();
            }

            long msToSleep = EVENT_HEARTBEAT_PERIOD - (System.currentTimeMillis() - t0);
            if (msToSleep<5)
                msToSleep = 5;
            waitNextLoop(msToSleep);
        }
    }
87649
def start(self):
        
        while True:
            self.thread_debug("Interval starting")
            for thr in threading.enumerate():
                self.thread_debug("    " + str(thr))
            self.feed_monitors()
            start = time.time()
            # wait fore queue to empty
            self.workers_queue.join()
            end = time.time()
            diff = self.config['interval']['test'] - (end - start)
            if diff <= 0:
                # alarm
                self.stats.procwin = -diff
                self.thread_debug("Cannot keep up with tests! {} seconds late"
                                  .format(abs(diff)))
            else:
                self.thread_debug("waiting {} seconds...".format(diff))
                time.sleep(diff)
750374
async def post_heartbeat(self, msg, _context):
        """"""

        name = msg.get('name')

        await self.service_manager.send_heartbeat(name)
1274236
function startInterval() {
    if (intervalId !== null) {
        return;
    }
    intervalId = setInterval(function () {
        if (remainedTasks.length && currentCount < limitCount) {
            var task = remainedTasks.shift();
            currentCount++;
            if (monitorCallback) {
                monitorCallback("start", remainedTasks);
            }
            var process = originalSpawn.apply(null, task[0]);
            process.on("close", function (code) {
                if (monitorCallback) {
                    monitorCallback("close", remainedTasks, code);
                }
                currentCount--;
                if (currentCount === 0 && remainedTasks.length === 0) {
                    callWaitAllCallbacks();
                }
            });
            var callback = remainedTaskCallbacks[task[1]];
            delete remainedTaskCallbacks[task[1]];
            if (callback) {
                callback(process);
            }
        }
    }, 20);
}
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));
    
  }
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
920053
def cli(obj, alert, severity, timeout, purge):
    """"""
    client = obj['client']

    if obj['output'] == 'json':
        r = client.http.get('/heartbeats')
        click.echo(json.dumps(r['heartbeats'], sort_keys=True, indent=4, ensure_ascii=False))
    else:
        timezone = obj['timezone']
        headers = {
            'id': 'ID', 'origin': 'ORIGIN', 'customer': 'CUSTOMER', 'tags': 'TAGS', 'createTime': 'CREATED',
            'receiveTime': 'RECEIVED', 'latency': 'LATENCY', 'timeout': 'TIMEOUT', 'since': 'SINCE', 'status': 'STATUS'
        }
        heartbeats = client.get_heartbeats()
        click.echo(tabulate([h.tabular(timezone) for h in heartbeats], headers=headers, tablefmt=obj['output']))

        not_ok = [hb for hb in heartbeats if hb.status != 'ok']
        if purge:
            with click.progressbar(not_ok, label='Purging {} heartbeats'.format(len(not_ok))) as bar:
                for b in bar:
                    client.delete_heartbeat(b.id)

        elif alert:
            with click.progressbar(heartbeats, label='Alerting {} heartbeats'.format(len(heartbeats))) as bar:
                for b in bar:
                    params = dict(filter(lambda a: len(a) == 2, map(lambda a: a.split(':'), b.tags)))
                    environment = params.get('environment', 'Production')
                    group = params.get('group', 'System')
                    tags = list(filter(lambda a: not a.startswith('environment:') and
                                       not a.startswith('group:'), b.tags))

                    if b.status == 'expired':  # aka. "stale"
                        client.send_alert(
                            resource=b.origin,
                            event='HeartbeatFail',
                            correlate=['HeartbeatFail', 'HeartbeatSlow', 'HeartbeatOK'],
                            group=group,
                            environment=environment,
                            service=['Alerta'],
                            severity=severity,
                            value='{}'.format(b.since),
                            text='Heartbeat not received in {} seconds'.format(b.timeout),
                            tags=tags,
                            type='heartbeatAlert',
                            timeout=timeout,
                            customer=b.customer
                        )
                    elif b.status == 'slow':
                        client.send_alert(
                            resource=b.origin,
                            event='HeartbeatSlow',
                            correlate=['HeartbeatFail', 'HeartbeatSlow', 'HeartbeatOK'],
                            group=group,
                            environment=environment,
                            service=['Alerta'],
                            severity=severity,
                            value='{}ms'.format(b.latency),
                            text='Heartbeat took more than {}ms to be processed'.format(MAX_LATENCY),
                            tags=tags,
                            type='heartbeatAlert',
                            timeout=timeout,
                            customer=b.customer
                        )
                    else:
                        client.send_alert(
                            resource=b.origin,
                            event='HeartbeatOK',
                            correlate=['HeartbeatFail', 'HeartbeatSlow', 'HeartbeatOK'],
                            group=group,
                            environment=environment,
                            service=['Alerta'],
                            severity='normal',
                            value='',
                            text='Heartbeat OK',
                            tags=tags,
                            type='heartbeatAlert',
                            customer=b.customer
                        )
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);
    }
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;
    }
1357534
def heartbeat(self):
        
        if self._rpc is not None and self._rpc.is_active:
            self._rpc.send(types.StreamingPullRequest())
257169
function (heartbeat, cb) {
        var self = this;
        this.swfClient.recordActivityTaskHeartbeat({
            taskToken: this.config.taskToken,
            details: stringify(heartbeat)
        }, function (err) {
            if (cb) {
                cb(err);
            }

        });
    }
902550
function PulseSensor (hardware, callback) {
  var self = this;

  // Set properties
  self.ready = false;
  self.hardware = hardware; // Hardware should be a specific pin for PulseSensor
  self.pollRate = 10; // Interval to read sensor
  self.arraySize = 3; // // BPM is calculated based on the average of an array of time differences. Increasing the array size smooths the data.
  self.array = [];
  self.BPM = 0; // Starts at 0, samples

  console.log('Collecting samples...');

  // Emit a time at each beat
  var high = false;
  setInterval(function () {
    if(self.readRaw() == 1) {
      if(!high) {
        high = true;
        var time = new Date(milliseconds);
        // TODO: add filtering
        self.emit('beat', time);
      }
    } else {
      high = false;
    }
  }, pollRate);

  // Collect for BPM
  var oldTime = new Date(milliseconds);
  self.on('beat', function (time) {
    var diff = time - oldTime
    // Check that the data is reasonable
    if (diff > 40 && diff < 5000) {
      self.array.push(time - oldTime);
    }
    oldTime = time;
    if(self.array.length > self.arraySize) {
      self.array.shift();
      var sum = 0;
      for (var i = 0; i < self.array.length; i++) {
        sum += self.array[i];
      }
      var avg = sum/self.array.length;
      self.BPM = 60000/avg;
      if (!self.ready) {
        if (self.BPM > 0) {
          self.ready = true;
          // Emit the ready event
          setImmediate(function emitReady() {
            self.emit('ready', self);
            if(callback) {
              callback(null, self);
            }
          });
        }
      }
    }
  });
}
550682
function sendHeartbeat() {
    _.forOwn(_this.socks, function (sock) {
      sock.write('hb');
    });
    setTimeout(sendHeartbeat, _this.heartbeatFreq);
  }
1337779
function() {
		this.pulse1.doSweep();
		this.pulse1.doLengthCounter();

		this.pulse2.doSweep();
		this.pulse2.doLengthCounter();

		this.triangle.doLengthCounter();

		this.noise.doLengthCounter();
		// TODO
	}
682944
function heartbeat() {
      Instance.db.updateOne(
        {
          _id: instanceId
        },
        {
          $set: { lastAliveOn: new Date() }
        },
        {
          upsert: true
        }
      );
    }
621468
def heartbeat(self):
        """"""
        while self._manager.is_active and not self._stop_event.is_set():
            self._manager.heartbeat()
            _LOGGER.debug("Sent heartbeat.")
            self._stop_event.wait(timeout=self._period)

        _LOGGER.info("%s exiting.", _HEARTBEAT_WORKER_NAME)