Skip to main content

timer

📅 2026-02-05 ✏️ 2026-03-06 CS GO
No related notes
go version
# go version go1.18.2 linux/amd64

0.0.1 · ticker#

func Tick(d Duration) <-chan Time

func NewTicker(d Duration) *Ticker

func (t *Ticker) Stop()

func (t *Ticker) Reset(d Duration)

0.0.2 · timer#

func After(d Duration) <-chan Time

func NewTimer(d Duration) *Timer

func AfterFunc(d Duration, f func()) *Timer

func (t *Timer) Stop() bool

func (t *Timer) Reset(d Duration) bool

0.0.2.1 · runtime#

//go:linkname localname importpath.name
type timer struct {
	// If this timer is on a heap, which P's heap it is on.
	// puintptr rather than *p to match uintptr in the versions
	// of this struct defined in other packages.
	pp puintptr // 指向P的指针

	// Timer wakes up at when, and then at when+period, ... (period > 0 only)
	// each time calling f(arg, now) in the timer goroutine, so f must be
	// a well-behaved function and not block.
	//
	// when must be positive on an active timer.
	when   int64 // 唤醒定时器的时间
	period int64 // 再次唤醒的间隔
	f      func(any, uintptr) // 每次唤醒定时器的回调函数
	arg    any // 与f相关
	seq    uintptr // 与f相关

	// What to set the when field to in timerModifiedXX status.
	nextwhen int64 // 在timerModifiedXX状态下,设置when的值; timer在不同P的堆上,在各自P给堆排序时,根据nextwhen设置when的值

	// The status field holds one of the values below.
	status uint32 // 定时器状态
}

runtime/timer.go#addtimer(): 添加一个timer到当前的P中。

runtime/timer.go#deltimer()

runtime/time.go#modtimer()

runtime/time.go#resettimer()

// resettimer resets the time when a timer should fire.
// If used for an inactive timer, the timer will become active.
// This should be called instead of addtimer if the timer value has been,
// or may have been, used previously.
// Reports whether the timer was modified before it was run.
// 重置timer的唤醒时间。
func resettimer(t *timer, when int64) bool {
	return modtimer(t, when, t.period, t.f, t.arg, t.seq)
}

runtime/time.go#clearntimers() runtime/time.go#adjusttimers() runtime/time.go#runtimer()