go语言time.Timer

发布时间 2023-04-25 18:54:33作者: 每天提醒自己要学习

go语言time.Timer

Timer是一个一次性的定时器,经过指定的时间后将会触发一个时间,通知调用的goroutine

使用方法

func main() {
	timer := time.NewTimer(3 * time.Second)

	for {
		select {
		case t := <-timer.C:
			fmt.Println(t)
			return
		}
	}
}

数据结构

Timer

// The Timer type represents a single event.
// When the Timer expires, the current time will be sent on C,
// unless the Timer was created by AfterFunc.
// A Timer must be created with NewTimer or AfterFunc.
type Timer struct {
	C <-chan Time
	r runtimeTimer
}

Timer代表一次事件,当Timer过期了,当前时间会被发送到channel C中,当Timer是AfterFunc方法创建时除外

  • C : 调用者可以通过此channel来接受时间
  • r : 系统管理的定时器

runtimeTimer

type runtimeTimer struct {
	pp       uintptr
	when     int64
	period   int64
	f        func(any, uintptr) // 
	arg      any
	seq      uintptr
	nextwhen int64
	status   uint32
}