// doTick handles the ticker goroutine of the timer system
3434
func (t *TimeoutWheel) doTick() {
	var expiredList timeoutList

	ticker := time.NewTicker(t.tickInterval)
	for range ticker.C {
		atomic.AddUint64(&t.ticks, 1)

		mtx := t.lockBucket(t.ticks)
		if t.state != running {
			mtx.Unlock()
			break
		}

		bucket := &t.buckets[t.ticks&t.bucketMask]
		timeout := bucket.head
		bucket.lastTick = t.ticks

		// find all the expired timeouts in the bucket.
		for timeout != nil {
			next := timeout.next
			if timeout.deadline <= t.ticks {
				timeout.state = timeoutExpired
				timeout.removeLocked()
				timeout.prependLocked(&expiredList)
			}
			timeout = next
		}

		mtx.Unlock()
		if expiredList.head == nil {
			continue
		}

		select {
		case t.calloutCh <- expiredList:
			expiredList.head = nil
		default:
		}
	}

	ticker.Stop()
}
1283102
func (cons *SimpleConsumer) TickerControlLoop(interval time.Duration, onTick func()) {
	cons.setState(PluginStateActive)
	go cons.tickerLoop(interval, onTick)
	cons.ControlLoop()
}
1000244
func (m *Machine) OnTimerTick(tickNonce int64) error {
	// Silently skip unexpected, late or canceled ticks. This is fine.
	switch {
	case m.State.IsSuspended():
		return nil
	case m.State.LastTick.TickNonce != tickNonce:
		return nil
	}

	// Report error (to trigger a retry) if the tick happened unexpectedly soon.
	// Allow up to 50ms clock drift, but correct it to be 0. This is important for
	// getting the correct next tick time from an absolute schedule. If we pass
	// m.Now to the cron schedule uncorrected, we'll just get the time of the
	// already scheduled tick (the one we are handling now, since uncorrected
	// m.Now is before it).
	//
	// Note that m.Now is part of inputs and must not be mutated. We propagate
	// the corrected time via the call stack.
	now := m.Now
	switch delay := now.Sub(m.State.LastTick.When); {
	case delay < -50*time.Millisecond:
		return fmt.Errorf("tick happened %s before it was expected", -delay)
	case delay < 0:
		now = m.State.LastTick.When
	}

	// The scheduled time has come!
	m.State.Generation = m.nextGen()
	m.Actions = append(m.Actions, StartInvocationAction{
		Generation: m.State.Generation,
	})
	m.State.LastTick = TickLaterAction{}

	// Start waiting for a new tick right away if on an absolute schedule or just
	// keep the tick state clear for relative schedules: new tick will be set when
	// RewindIfNecessary() is manually called by whoever handles the cron.
	if m.Schedule.IsAbsolute() {
		m.rewindIfNecessary(now)
	}

	return nil
}
946110
func (t *Ticker) Run() {
	var (
		i, pos, line, fieldNum int
		n                      uint64
		v                      byte
		err                    error
		cur                    structs.DevInfo
		dev                 structs.Device
	)
	// ticker
	for {
		select {
		case <-t.Done:
			return
		case <-t.C:
			cur.Timestamp = time.Now().UTC().UnixNano()
			err = t.Reset()
			if err != nil {
				t.Errs <- err
				break
			}
			line = 0
			cur.Device = cur.Device[:0]
			// read each line until eof
			for {
				t.Val = t.Val[:0]
				t.Line, err = t.ReadSlice('\n')
				if err != nil {
					if err == io.EOF {
						break
					}
					t.Errs <- &joe.ReadError{Err: err}
					break
				}
				line++
				if line < 3 {
					continue
				}
				// first grab the interface name (everything up to the ':')
				for i, v = range t.Line {
					if v == 0x3A {
						pos = i + 1
						break
					}
					// skip spaces
					if v != 0x20 {
						continue
					}
					t.Val = append(t.Val, v)
				}
				dev.Name = string(t.Val[:])
				fieldNum = 0
				// process the rest of the line
				for {
					fieldNum++
					// skip all spaces
					for i, v = range t.Line[pos:] {
						if v != 0x20 {
							pos += i
							break
						}
					}
					// grab the numbers
					for i, v = range t.Line[pos:] {
						if v == 0x20 || v == '\n' {
							break
						}
					}
					// any conversion error results in 0
					n, err = helpers.ParseUint(t.Line[pos : pos+1])
					pos += i
					if err != nil {
						t.Errs <- &joe.ParseError{Info: fmt.Sprintf("line %d: field %d", line, fieldNum), Err: err}
						continue
					}
					if fieldNum < 9 {
						if fieldNum < 5 {
							if fieldNum < 3 {
								if fieldNum == 1 {
									dev.RBytes = int64(n)
									continue
								}
								dev.RPackets = int64(n) // must be 2
								continue
							}
							if fieldNum == 3 {
								dev.RErrs = int64(n)
								continue
							}
							dev.RDrop = int64(n) // must be 4
							continue
						}
						if fieldNum < 7 {
							if fieldNum == 5 {
								dev.RFIFO = int64(n)
								continue
							}
							dev.RFrame = int64(n) // must be 6
							continue
						}
						if fieldNum == 7 {
							dev.RCompressed = int64(n)
							continue
						}
						dev.RMulticast = int64(n) // must be 8
						continue
					}
					if fieldNum < 13 {
						if fieldNum < 11 {
							if fieldNum == 9 {
								dev.TBytes = int64(n)
								continue
							}
							dev.TPackets = int64(n) // must be 10
							continue
						}
						if fieldNum == 11 {
							dev.TErrs = int64(n)
							continue
						}
						dev.TDrop = int64(n) // must be 12
						continue
					}
					if fieldNum < 15 {
						if fieldNum == 13 {
							dev.TFIFO = int64(n)
							continue
						}
						dev.TColls = int64(n) // must be 14
						continue
					}
					if fieldNum == 15 {
						dev.TCarrier = int64(n)
						continue
					}
					if fieldNum == 16 {
						dev.TCompressed = int64(n)
						break
					}
				}
				cur.Device = append(cur.Device, dev)
			}
			t.Data <- t.CalculateUsage(&cur)
			t.prior.Timestamp = cur.Timestamp
			if len(t.prior.Device) != len(cur.Device) {
				t.prior.Device = make([]structs.Device, len(cur.Device))
			}
			copy(t.prior.Device, cur.Device)
		}
	}
}
706086
func dotEdge(rpt *Report, from, to int, e *edgeInfo) string {
	w := rpt.formatValue(e.weight)
	attr := fmt.Sprintf(`label=" %s"`, w)
	if rpt.total > 0 {
		if weight := 1 + int(e.weight*100/rpt.total); weight > 1 {
			attr = fmt.Sprintf(`%s weight=%d`, attr, weight)
		}
		if width := 1 + int(e.weight*5/rpt.total); width > 1 {
			attr = fmt.Sprintf(`%s penwidth=%d`, attr, width)
		}
	}
	arrow := "->"
	if e.residual {
		arrow = "..."
	}
	tooltip := fmt.Sprintf(`"%s %s %s (%s)"`,
		e.src.info.prettyName(), arrow, e.dest.info.prettyName(), w)
	attr = fmt.Sprintf(`%s tooltip=%s labeltooltip=%s`,
		attr, tooltip, tooltip)

	if e.residual {
		attr = attr + ` style="dotted"`
	}

	if len(e.src.tags) > 0 {
		// Separate children further if source has tags.
		attr = attr + " minlen=2"
	}
	return fmt.Sprintf("N%d -> N%d [%s]", from, to, attr)
}
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():]
		}
	}
}
767195
func (e *engineImpl) execCronTickTask(c context.Context, tqTask proto.Message) error {
	msg := tqTask.(*internal.CronTickTask)
	return e.jobTxn(c, msg.JobId, func(c context.Context, job *Job, isNew bool) error {
		if isNew {
			logging.Errorf(c, "Scheduled job is unexpectedly gone")
			return errSkipPut
		}
		logging.Infof(c, "Tick %d has arrived", msg.TickNonce)
		return pokeCron(c, job, e.cfg.Dispatcher, func(m *cron.Machine) error {
			// OnTimerTick returns an error if the tick happened too soon. Mark this
			// error as transient to trigger task queue retry at a later time.
			return transient.Tag.Apply(m.OnTimerTick(msg.TickNonce))
		})
	})
}
564677
func pidWait(pid int) error {
	ticker := time.NewTicker(1 * time.Second)
	defer ticker.Stop()

	for range ticker.C {
		if !pidAlive(pid) {
			break
		}
	}

	return nil
}
1222816
func (c *Cubic) CongestionWindowAfterAck(
	ackedBytes protocol.ByteCount,
	currentCongestionWindow protocol.ByteCount,
	delayMin time.Duration,
	eventTime time.Time,
) protocol.ByteCount {
	c.ackedBytesCount += ackedBytes

	if c.epoch.IsZero() {
		// First ACK after a loss event.
		c.epoch = eventTime            // Start of epoch.
		c.ackedBytesCount = ackedBytes // Reset count.
		// Reset estimated_tcp_congestion_window_ to be in sync with cubic.
		c.estimatedTCPcongestionWindow = currentCongestionWindow
		if c.lastMaxCongestionWindow <= currentCongestionWindow {
			c.timeToOriginPoint = 0
			c.originPointCongestionWindow = currentCongestionWindow
		} else {
			c.timeToOriginPoint = uint32(math.Cbrt(float64(cubeFactor * (c.lastMaxCongestionWindow - currentCongestionWindow))))
			c.originPointCongestionWindow = c.lastMaxCongestionWindow
		}
	}

	// Change the time unit from microseconds to 2^10 fractions per second. Take
	// the round trip time in account. This is done to allow us to use shift as a
	// divide operator.
	elapsedTime := int64(eventTime.Add(delayMin).Sub(c.epoch)/time.Microsecond) << 10 / (1000 * 1000)

	// Right-shifts of negative, signed numbers have implementation-dependent
	// behavior, so force the offset to be positive, as is done in the kernel.
	offset := int64(c.timeToOriginPoint) - elapsedTime
	if offset < 0 {
		offset = -offset
	}

	deltaCongestionWindow := protocol.ByteCount(cubeCongestionWindowScale*offset*offset*offset) * protocol.DefaultTCPMSS >> cubeScale
	var targetCongestionWindow protocol.ByteCount
	if elapsedTime > int64(c.timeToOriginPoint) {
		targetCongestionWindow = c.originPointCongestionWindow + deltaCongestionWindow
	} else {
		targetCongestionWindow = c.originPointCongestionWindow - deltaCongestionWindow
	}
	// Limit the CWND increase to half the acked bytes.
	targetCongestionWindow = utils.MinByteCount(targetCongestionWindow, currentCongestionWindow+c.ackedBytesCount/2)

	// Increase the window by approximately Alpha * 1 MSS of bytes every
	// time we ack an estimated tcp window of bytes.  For small
	// congestion windows (less than 25), the formula below will
	// increase slightly slower than linearly per estimated tcp window
	// of bytes.
	c.estimatedTCPcongestionWindow += protocol.ByteCount(float32(c.ackedBytesCount) * c.alpha() * float32(protocol.DefaultTCPMSS) / float32(c.estimatedTCPcongestionWindow))
	c.ackedBytesCount = 0

	// We have a new cubic congestion window.
	c.lastTargetCongestionWindow = targetCongestionWindow

	// Compute target congestion_window based on cubic target and estimated TCP
	// congestion_window, use highest (fastest).
	if targetCongestionWindow < c.estimatedTCPcongestionWindow {
		targetCongestionWindow = c.estimatedTCPcongestionWindow
	}
	return targetCongestionWindow
}
576729
func (bot *ExchangeBot) nextTick() *time.Timer {
	tNow := time.Now()
	tOldest := tNow
	for _, xc := range bot.Exchanges {
		t := xc.LastTry()
		if t.Before(tOldest) {
			tOldest = t
		}
	}
	tSince := tNow.Sub(tOldest)
	tilNext := bot.DataExpiry - tSince
	if tilNext < bot.minTick {
		tilNext = bot.minTick
	}
	return time.NewTimer(tilNext)
}
678761
func (prod *DirectProducer) TickerMessageControlLoop(onMessage func(*Message),
	interval time.Duration, onTimeOut func()) {
	prod.setState(PluginStateActive)
	prod.onMessage = onMessage
	prod.TickerControlLoop(interval, onTimeOut)
}
935651
func (t *Ticker) tick() {
	for {
		select {
		case tick := <-t.ticker.C:
			t.mux.Lock()
			for i := range t.chans {
				select {
				case t.chans[i] <- tick:
				default:
					t.dropped++
				}
			}
			t.mux.Unlock()
		case <-t.stopCh:
			return
		}
	}
}
235943
func defaultDoDelay(ctx context.Context, delay time.Duration) error {
	if delay == 0 {
		return nil
	}

	timer := time.NewTimer(delay)
	select {
	case <-timer.C:
		return nil
	case <-ctx.Done():
		timer.Stop()
		return errors.WithStack(ctx.Err())
	}
}
632495
func eventAddTimeoutFunc(freq C.int, callback uintptr, opaque uintptr, free uintptr) C.int {
	if eventLoopImpl == nil {
		panic("Event loop impl is missing")
	}

	cbinfo := &EventTimeoutCallbackInfo{
		callback: callback,
		opaque:   opaque,
		free:     free,
	}

	return C.int(eventLoopImpl.AddTimeoutFunc(int(freq), cbinfo))
}
817494
func ticker(d time.Duration) chan struct{} {
	t := time.NewTicker(d)
	stop := make(chan struct{})
	go func() {
		for {
			select {
			case <-t.C:
				log.Printf("tick (just for keeping CI job active) per %s", d.String())
			case <-stop:
				t.Stop()
			}
		}
	}()
	return stop
}
682879
func (c *Client) healthchecker() {
	c.mu.RLock()
	timeout := c.healthcheckTimeout
	interval := c.healthcheckInterval
	c.mu.RUnlock()

	ticker := time.NewTicker(interval)
	defer ticker.Stop()

	for {
		select {
		case <-c.healthcheckStop:
			// we are asked to stop, so we signal back that we're stopping now
			c.healthcheckStop <- true
			return
		case <-ticker.C:
			c.healthcheck(context.Background(), timeout, false)
		}
	}
}
1165279
func (b *EvalBroker) flush() {
	b.l.Lock()
	defer b.l.Unlock()

	// Unblock any waiters
	for _, waitCh := range b.waiting {
		close(waitCh)
	}
	b.waiting = make(map[string]chan struct{})

	// Cancel any Nack timers
	for _, unack := range b.unack {
		unack.NackTimer.Stop()
	}

	// Cancel any time wait evals
	for _, wait := range b.timeWait {
		wait.Stop()
	}

	// Cancel the delayed evaluations goroutine
	if b.delayedEvalCancelFunc != nil {
		b.delayedEvalCancelFunc()
	}

	// Clear out the update channel for delayed evaluations
	b.delayedEvalsUpdateCh = make(chan struct{}, 1)

	// Reset the broker
	b.stats.TotalReady = 0
	b.stats.TotalUnacked = 0
	b.stats.TotalBlocked = 0
	b.stats.TotalWaiting = 0
	b.stats.ByScheduler = make(map[string]*SchedulerStats)
	b.evals = make(map[string]int)
	b.jobEvals = make(map[structs.NamespacedID]string)
	b.blocked = make(map[structs.NamespacedID]PendingEvaluations)
	b.ready = make(map[string]PendingEvaluations)
	b.unack = make(map[string]*unackEval)
	b.timeWait = make(map[string]*time.Timer)
	b.delayHeap = delayheap.NewDelayHeap()
}