zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Go 语言一次性定时器使用方式和实现原理

Go语言原理 实现 使用 方式 定时器 一次性
2023-06-13 09:14:09 时间

01

介绍

在 Go 语言标准库 time 包中的 Timer 类型,它是表示单一事件的计时器,也就是说它是一次性定时器。

在 Go 语言项目开发中,定时器使用广泛,本文我们介绍 Go 语言中怎么使用 Timer,以及它的实现原理。

02

使用方式

使用 Timer 一次性定时器,需要导入 time 包,创建定时器的方式有两种,分别是:

func NewTimer(d Duration) *Timer

使用 func NewTimer 创建 Timer,入参是定时器的等待时间,时间到达时,发送当前时间到 channel中。

示例代码:

func main() {
 nowTime := time.Now().Unix()
 fmt.Println(nowTime)
 NewTimerDemo()
}

func NewTimerDemo() {
 timer := time.NewTimer(2 * time.Second)
 select {
 case <-timer.C:
  currentTime := time.Now().Unix()
  fmt.Println(currentTime, "do something")
 }
}

输出结果:

1665894136
1665894138 do something

通过阅读上面这段代码,我们可以发现我们定义了一个 2s 后执行的定时器 timer,然后使用 select 读取 timer.C 中的数据,当读取到数据时,执行特定业务逻辑代码。

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

使用 func AfterFunc 创建 Timer,入参是定时器等待时间,和时间到达时执行的函数。

示例代码:

func main() {
 nowTime := time.Now().Unix()
 fmt.Println(nowTime)
 AfterFuncDemo()
}

func AfterFuncDemo() {
 time.AfterFunc(2 * time.Second, func() {
  currentTime := time.Now().Unix()
  fmt.Println(currentTime, "do something")
 })
 time.Sleep(3 * time.Second)
}

阅读上面这段代码,细心的读者朋友们可能已经发现,我们在代码末尾使用 time.Sleep(),这是因为 time.AfterFunc() 是异步执行的,所以需要等待协成退出。

03

实现原理

我们在源码中查看 Timer 的数据结构,发现它包含两个字段,其中一个是可导出字段 C,这是一个 Time类型的 chan;另一个是不可导出字段 r,这是一个 runtimeTimer 类型。

type Timer struct {
    C <-chan Time
    r runtimeTimer
}

实际上,每个 Go 应用程序底层都会有一个特定的协程管理 Timer,该协程(底层协程)监控到某个 Timer 指定的时间到达时,就会将当前时间发送到 C 中,然后上层读取到 C 中的数据时,执行相关业务逻辑代码。

底层协程监控 Timerr 字段中的数据,我们在源码中查看一下 runtimeTimer 的数据结构:

type runtimeTimer struct {
    tb     uintptr
    i      int
    when   int64
    period int64
    f      func(interface{}, uintptr)
    arg    interface{}
    seq    uintptr
}

阅读上面这段代码,我们可以发现 runtimeTimer 中包含的所有字段,我们重点了解 whenfarg

  • when:定时器执行时间。
  • f:定时器执行的回调函数。
  • arg:定时器执行的回调函数的参数。

在简单了解 Timer 的数据结构之后,我们在源码中查看一下 func NewTimer 的代码:

// NewTimer creates a new Timer that will send
// the current time on its channel after at least duration d.
func NewTimer(d Duration) *Timer {
 c := make(chan Time, 1)
 t := &Timer{
  C: c,
  r: runtimeTimer{
   when: when(d),
   f:    sendTime,
   arg:  c,
  },
 }
 startTimer(&t.r)
 return t
}

阅读上面这段代码,我们可以发现 func NewTimer 的实现非常简单,它实际上就是构造了一个 Timer,然后把 Timer.r 传参给 startTimer(),除了 startTimer() 函数外,还有两个函数,分别是 when()sendTime,其中 when() 是计算计时器的执行时间,sendTime 是计时器时间到达时执行的事件(实际上就是将当前时间写入通道中)。

sendTime 源码:

func sendTime(c interface{}, seq uintptr) {
 // Non-blocking send of time on c.
 // Used in NewTimer, it cannot block anyway (buffer).
 // Used in NewTicker, dropping sends on the floor is
 // the desired behavior when the reader gets behind,
 // because the sends are periodic.
 select {
 case c.(chan Time) <- Now():
 default:
 }
}

我们已经了解到,func NewTimer 将构造的 Timer.r 传参给 startTimer(),它负责把 runtimeTimer写入底层协程的数组中(如果底层协程未运行,它将会启动底层协程),将 Timer 交给底层协程监控,也就是上面讲到的,当底层协程监控到某个 Timer 指定时间到达时,将当前时间发送到它的通道中。

// startTimer adds t to the timer heap.
//go:linkname startTimer time.startTimer
func startTimer(t *timer) {
 if raceenabled {
  racerelease(unsafe.Pointer(t))
 }
 addtimer(t)
}

04

总结

本文我们介绍 Go 语言标准库 time 包提供的一次性定时器 Timer,不仅介绍了它的使用方式,还介绍了它的实现原理。

限于篇幅,本文没有介绍 Stop()Reset() 方法,感兴趣的读者朋友们可以查阅相关资料。

推荐阅读:

  1. Go 语言怎么解决编译器错误遮蔽?
  2. Golang 语言的多种变量声明方式和使用场景
  3. Golang 语言中基础同步原语 Mutex 和 RWMutex 的区别
  4. Golang 语言怎么使用 panic 函数?
  5. Golang 语言的标准库 log 包怎么使用?

参考资料:

  1. https://pkg.go.dev/time#Timer
  2. https://gobyexample.com/timers