/*
	The heart beat receive ticker.
*/
349792
func (c *Connection) receiveTicker() {
	c.hbd.rc = 0
	var first, last, nd int64
hbGet:
	for {
		nd = c.hbd.rti - (last - first)
		// Check if receives are supposed to be "fast" *and* we spent a
		// lot of time in the previous loop.
		if nd <= 0 {
			nd = c.hbd.rti
		}
		ticker := time.NewTicker(time.Duration(nd))
		select {
		case ct := <-ticker.C:
			first = time.Now().UnixNano()
			ticker.Stop()
			c.hbd.rdl.Lock()
			flr := c.hbd.lr
			ld := ct.UnixNano() - flr
			c.log("HeartBeat Receive TIC", "TickerVal", ct.UnixNano(),
				"LastReceive", flr, "Diff", ld)
			if ld > (c.hbd.rti + (c.hbd.rti / 5)) { // swag plus to be tolerant
				c.log("HeartBeat Receive Read is dirty")
				c.Hbrf = true // Flag possible dirty connection
			} else {
				c.Hbrf = false // Reset
				c.hbd.rc++
			}
			c.hbd.rdl.Unlock()
			last = time.Now().UnixNano()
		case _ = <-c.hbd.rsd:
			ticker.Stop()
			break hbGet
		case _ = <-c.ssdc:
			ticker.Stop()
			break hbGet
		} // End of select
	} // End of for
	c.log("Heartbeat Receive Ends", time.Now())
	return
}
132140
func (h *nodeHeartbeater) resetHeartbeatTimerLocked(id string, ttl time.Duration) {
	// Ensure a timer map exists
	if h.heartbeatTimers == nil {
		h.heartbeatTimers = make(map[string]*time.Timer)
	}

	// Renew the heartbeat timer if it exists
	if timer, ok := h.heartbeatTimers[id]; ok {
		timer.Reset(ttl)
		return
	}

	// Create a new timer to track expiration of this heartbeat
	timer := time.AfterFunc(ttl, func() {
		h.invalidateHeartbeat(id)
	})
	h.heartbeatTimers[id] = timer
}
246108
func (c *forwardingClient) startHeartbeat() {
	go func() {
		tick := func() {
			c.core.stateLock.RLock()
			clusterAddr := c.core.clusterAddr
			c.core.stateLock.RUnlock()

			ctx, cancel := context.WithTimeout(c.echoContext, 2*time.Second)
			resp, err := c.RequestForwardingClient.Echo(ctx, &EchoRequest{
				Message:     "ping",
				ClusterAddr: clusterAddr,
			})
			cancel()
			if err != nil {
				c.core.logger.Debug("forwarding: error sending echo request to active node", "error", err)
				return
			}
			if resp == nil {
				c.core.logger.Debug("forwarding: empty echo response from active node")
				return
			}
			if resp.Message != "pong" {
				c.core.logger.Debug("forwarding: unexpected echo response from active node", "message", resp.Message)
				return
			}
			// Store the active node's replication state to display in
			// sys/health calls
			atomic.StoreUint32(c.core.activeNodeReplicationState, resp.ReplicationState)
		}

		tick()

		for {
			select {
			case <-c.echoContext.Done():
				c.echoTicker.Stop()
				c.core.logger.Debug("forwarding: stopping heartbeating")
				atomic.StoreUint32(c.core.activeNodeReplicationState, uint32(consts.ReplicationUnknown))
				return
			case <-c.echoTicker.C:
				tick()
			}
		}
	}()
}
1206404
func (s *TickScheduler) Tick(now int64) {
	s.schedulerMu.Lock()
	defer s.schedulerMu.Unlock()

	if s.ctx == nil {
		return
	}

	select {
	case <-s.ctx.Done():
		return
	default:
		// do nothing and allow ticks
	}

	atomic.StoreInt64(&s.now, now)

	affected := 0
	for _, ts := range s.taskSchedulers {
		if nextDue, hasQueue := ts.NextDue(); now >= nextDue || hasQueue {
			ts.Work()
			affected++
		}
	}
	// TODO(mr): find a way to emit a more useful / less annoying tick message, maybe aggregated over the past 10s or 30s?
	s.logger.Debug("Ticked", zap.Int64("now", now), zap.Int("tasks_affected", affected))
}
429246
func (b *Broker) Heartbeat(request *HeartbeatRequest) (*HeartbeatResponse, error) {
	response := new(HeartbeatResponse)

	err := b.sendAndReceive(request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}
176730
func check(hrt heart.Heart, ttl time.Duration) (idx uint64, err error) {
	// time out after a third of the machine presence TTL, attempting
	// the heartbeat up to four times
	timeout := ttl / 3
	interval := timeout / 4

	tchan := time.After(timeout)
	next := time.After(0)
	for idx == 0 {
		select {
		case <-tchan:
			err = errors.New("Monitor timed out before successful heartbeat")
			return
		case <-next:
			idx, err = hrt.Beat(ttl)
			if err != nil {
				log.Debugf("Monitor heartbeat function returned err, retrying in %v: %v", interval, err)
			}

			next = time.After(interval)
		}
	}

	return
}
1086353
func heartBeat(session *yamux.Session) {
	if session == nil {
		return
	}

	for {
		if session.IsClosed() {
			break
		}

		session.Ping()

		// 1 Hz heartbeat
		time.Sleep(time.Second)
	}
}
264156
func (nm *NodeMonitor) SendEvent(typ int, event interface{}) error {
	var buf bytes.Buffer

	if err := gob.NewEncoder(&buf).Encode(event); err != nil {
		nm.bumpLost()
		return fmt.Errorf("Unable to gob encode: %s", err)
	}

	select {
	case nm.queue <- append([]byte{byte(typ)}, buf.Bytes()...):
	default:
		nm.bumpLost()
		return fmt.Errorf("Monitor queue is full, discarding notification")
	}

	return nil
}
1080994
func (c *Connection) heartbeater(interval time.Duration, done chan *Error) {
	const maxServerHeartbeatsInFlight = 3

	var sendTicks <-chan time.Time
	if interval > 0 {
		ticker := time.NewTicker(interval)
		defer ticker.Stop()
		sendTicks = ticker.C
	}

	lastSent := time.Now()

	for {
		select {
		case at, stillSending := <-c.sends:
			// When actively sending, depend on sent frames to reset server timer
			if stillSending {
				lastSent = at
			} else {
				return
			}

		case at := <-sendTicks:
			// When idle, fill the space with a heartbeat frame
			if at.Sub(lastSent) > interval-time.Second {
				if err := c.send(&heartbeatFrame{}); err != nil {
					// send heartbeats even after close/closeOk so we
					// tick until the connection starts erroring
					return
				}
			}

		case conn := <-c.deadlines:
			// When reading, reset our side of the deadline, if we've negotiated one with
			// a deadline that covers at least 2 server heartbeats
			if interval > 0 {
				conn.SetReadDeadline(time.Now().Add(maxServerHeartbeatsInFlight * interval))
			}

		case <-done:
			return
		}
	}
}
314164
func (t *Ticker) Run() {
	// predeclare some vars
	var (
		i, pos, nameLen int
		v               byte
		n               uint64
		err             error
	)
	// ticker
Tick:
	for {
		select {
		case <-t.Done:
			return
		case <-t.C:
			t.Builder.Reset()
			err = t.Profiler.Profiler.Reset()
			if err != nil {
				t.Errs <- err
				continue
			}
			structs.InfoStart(t.Builder)
			structs.InfoAddTimestamp(t.Builder, time.Now().UTC().UnixNano())
			for {
				t.Val = t.Val[:0]
				t.Line, err = t.ReadSlice('\n')
				if err != nil {
					if err == io.EOF {
						break
					}
					// An error results in sending error message and stop processing of this tick.
					t.Errs <- &joe.ReadError{Err: err}
					continue Tick
				}
				// first grab the key name (everything up to the ':')
				for i, v = range t.Line {
					if v == 0x3A {
						t.Val = t.Line[:i]
						pos = i + 1 // skip the :
						break
					}
				}
				nameLen = len(t.Val)
				// skip all spaces
				for i, v = range t.Line[pos:] {
					if v != 0x20 {
						pos += i
						break
					}
				}

				// grab the numbers
				for _, v = range t.Line[pos:] {
					if v == 0x20 || v == '\n' {
						break
					}
					t.Val = append(t.Val, v)
				}
				// any conversion error results in 0
				n, err = helpers.ParseUint(t.Val[nameLen:])
				if err != nil {
					t.Errs <- &joe.ParseError{Info: string(t.Val[:nameLen]), Err: err}
					continue
				}
				v = t.Val[0]
				if v == 'A' {
					if t.Val[5] == 'e' {
						if nameLen == 6 {
							structs.InfoAddActive(t.Builder, n)
							continue
						}
						if t.Val[7] == 'a' {
							structs.InfoAddActiveAnon(t.Builder, n)
							continue
						}
						structs.InfoAddActiveFile(t.Builder, n)
						continue
					}
					if nameLen == 9 {
						structs.InfoAddAnonPages(t.Builder, n)
						continue
					}
					structs.InfoAddAnonHugePages(t.Builder, n)
					continue
				}
				if v == 'C' {
					if nameLen == 6 {
						structs.InfoAddCached(t.Builder, n)
						continue
					}
					if nameLen == 11 {
						structs.InfoAddCommitLimit(t.Builder, n)
						continue
					}
					structs.InfoAddCommittedAS(t.Builder, n)
					continue
				}
				if v == 'D' {
					if nameLen == 5 {
						structs.InfoAddDirty(t.Builder, n)
						continue
					}
					if t.Val[10] == 'k' {
						structs.InfoAddDirectMap4K(t.Builder, n)
						continue
					}
					structs.InfoAddDirectMap2M(t.Builder, n)
					continue
				}
				if v == 'H' {
					if nameLen == 14 {
						if t.Val[10] == 'F' {
							structs.InfoAddHugePagesFree(t.Builder, n)
							continue
						}
						if t.Val[10] == 'R' {
							structs.InfoAddHugePagesRsvd(t.Builder, n)
							continue
						}
						structs.InfoAddHugePagesSurp(t.Builder, n)
					}
					if t.Val[1] == 'a' {
						structs.InfoAddHardwareCorrupted(t.Builder, n)
						continue
					}
					if t.Val[9] == 'i' {
						structs.InfoAddHugePagesSize(t.Builder, n)
						continue
					}
					structs.InfoAddHugePagesTotal(t.Builder, n)
					continue
				}
				if v == 'I' {
					if nameLen == 8 {
						structs.InfoAddInactive(t.Builder, n)
						continue
					}
					if t.Val[9] == 'a' {
						structs.InfoAddInactiveAnon(t.Builder, n)
						continue
					}
					structs.InfoAddInactiveFile(t.Builder, n)
				}
				if v == 'M' {
					v = t.Val[3]
					if nameLen < 8 {
						if v == 'p' {
							structs.InfoAddMapped(t.Builder, n)
							continue
						}
						if v == 'F' {
							structs.InfoAddMemFree(t.Builder, n)
							continue
						}
						structs.InfoAddMlocked(t.Builder, n)
						continue
					}
					if v == 'A' {
						structs.InfoAddMemAvailable(t.Builder, n)
						continue
					}
					structs.InfoAddMemTotal(t.Builder, n)
					continue
				}
				if v == 'S' {
					v = t.Val[1]
					if v == 'w' {
						if t.Val[4] == 'C' {
							structs.InfoAddSwapCached(t.Builder, n)
							continue
						}
						if t.Val[4] == 'F' {
							structs.InfoAddSwapFree(t.Builder, n)
							continue
						}
						structs.InfoAddSwapTotal(t.Builder, n)
						continue
					}
					if v == 'h' {
						structs.InfoAddShmem(t.Builder, n)
						continue
					}
					if v == 'l' {
						structs.InfoAddSlab(t.Builder, n)
						continue
					}
					if v == 'R' {
						structs.InfoAddSReclaimable(t.Builder, n)
						continue
					}
					structs.InfoAddSUnreclaim(t.Builder, n)
					continue
				}
				if v == 'V' {
					if t.Val[8] == 'C' {
						structs.InfoAddVmallocChunk(t.Builder, n)
						continue
					}
					if t.Val[8] == 'T' {
						structs.InfoAddVmallocTotal(t.Builder, n)
						continue
					}
					structs.InfoAddVmallocUsed(t.Builder, n)
					continue
				}
				if v == 'W' {
					if nameLen == 9 {
						structs.InfoAddWriteback(t.Builder, n)
						continue
					}
					structs.InfoAddWritebackTmp(t.Builder, n)
					continue
				}
				if v == 'B' {
					if nameLen == 6 {
						structs.InfoAddBounce(t.Builder, n)
						continue
					}
					structs.InfoAddBuffers(t.Builder, n)
					continue
				}
				if v == 'K' {
					structs.InfoAddKernelStack(t.Builder, n)
					continue
				}
				if v == 'N' {
					structs.InfoAddNFSUnstable(t.Builder, n)
					continue
				}
				if v == 'P' {
					structs.InfoAddPageTables(t.Builder, n)
				}
				structs.InfoAddUnevictable(t.Builder, n)
			}
			t.Builder.Finish(structs.InfoEnd(t.Builder))
			t.Data <- t.Profiler.Builder.Bytes[t.Builder.Head():]
		}
	}
}
807151
func Tick() {
	now := time.Now()
	timerHeapLock.Lock()

	for {
		if timerHeap.Len() <= 0 {
			break
		}

		nextFireTime := timerHeap.timers[0].fireTime
		//fmt.Printf(">>> nextFireTime %s, now is %s\n", nextFireTime, now)
		if nextFireTime.After(now) {
			break
		}

		t := heap.Pop(&timerHeap).(*Timer)

		callback := t.callback
		if callback == nil {
			continue
		}

		if !t.repeat {
			t.callback = nil
		}
		// unlock the lock to run callback, because callback may add more callbacks / timers
		timerHeapLock.Unlock()
		runCallback(callback)
		timerHeapLock.Lock()

		if t.repeat {
			// add Timer back to heap
			t.fireTime = t.fireTime.Add(t.interval)
			if !t.fireTime.After(now) { // might happen when interval is very small
				t.fireTime = now.Add(t.interval)
			}
			t.addseq = nextAddSeq
			nextAddSeq += 1
			heap.Push(&timerHeap, t)
		}
	}
	timerHeapLock.Unlock()
}
159345
func (w *trezorDriver) Heartbeat() error {
	if _, err := w.trezorExchange(&trezor.Ping{}, new(trezor.Success)); err != nil {
		w.failure = err
		return err
	}
	return nil
}
246673
func (c *ringShards) Heartbeat(frequency time.Duration) {
	ticker := time.NewTicker(frequency)
	defer ticker.Stop()
	for range ticker.C {
		var rebalance bool

		c.mu.RLock()

		if c.closed {
			c.mu.RUnlock()
			break
		}

		shards := c.list
		c.mu.RUnlock()

		for _, shard := range shards {
			err := shard.Client.Ping().Err()
			if shard.Vote(err == nil || err == pool.ErrPoolTimeout) {
				internal.Logf("ring shard state changed: %s", shard)
				rebalance = true
			}
		}

		if rebalance {
			c.rebalance()
		}
	}
}
392240
func (r *Reader) readHeartbeat() {
	defer tabletenv.LogError()

	ctx, cancel := context.WithDeadline(context.Background(), r.now().Add(r.interval))
	defer cancel()

	res, err := r.fetchMostRecentHeartbeat(ctx)
	if err != nil {
		r.recordError(vterrors.Wrap(err, "Failed to read most recent heartbeat"))
		return
	}
	ts, err := parseHeartbeatResult(res)
	if err != nil {
		r.recordError(vterrors.Wrap(err, "Failed to parse heartbeat result"))
		return
	}

	lag := r.now().Sub(time.Unix(0, ts))
	cumulativeLagNs.Add(lag.Nanoseconds())
	currentLagNs.Set(lag.Nanoseconds())
	reads.Add(1)

	r.lagMu.Lock()
	r.lastKnownLag = lag
	r.lastKnownError = nil
	r.lagMu.Unlock()
}
391757
func NewTicker(last time.Time, initialOffset time.Duration, c clock.Clock) *Ticker {
	t := &Ticker{
		C:         make(chan time.Time),
		clock:     c,
		last:      last,
		offset:    initialOffset,
		newOffset: make(chan time.Duration),
	}
	go t.run()
	return t
}
403261
func (sc *conn) processHeartBeat(m *nats.Msg) {
	// No payload assumed, just reply.
	sc.RLock()
	nc := sc.nc
	sc.RUnlock()
	if nc != nil {
		nc.Publish(m.Reply, nil)
	}
}
254583
func (c *Callbacks) OnCNETMsg_Tick(fn func(*dota.CNETMsg_Tick) error) {
	c.onCNETMsg_Tick = append(c.onCNETMsg_Tick, fn)
}