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

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

​1.介绍

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

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

2.使用方式

使用 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() 是异步执行的,所以需要等待协成退出。

3.实现原理

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

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

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

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

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

阅读上面这段代码,我们可以发现 runtimeTimer​ 中包含的所有字段,我们重点了解 when、f​ 和 arg。

  • 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)
}

4.总结

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

责任编辑:武晓燕 来源: Golang语言开发栈
相关推荐

2023-09-26 07:11:15

KubernetesJob节点

2022-10-24 00:48:58

Go语言errgroup

2014-03-06 15:16:18

安全管理linux安全

2010-11-24 16:32:50

2013-04-17 09:16:37

2024-02-28 08:18:13

Java日志项目

2014-08-04 14:38:25

LinuxToken

2019-08-06 09:21:45

2021-08-12 09:48:21

Webpack Loa工具Webpack

2021-09-02 07:26:27

Django 验证码Framework

2012-09-18 15:04:31

Office 2013微软

2009-12-25 14:46:53

Windows 7文件关联

2017-03-13 09:24:59

概念学习器学习字符

2021-07-26 09:56:19

AI 数据人工智能

2012-02-01 16:48:54

后门Putty

2011-04-18 13:36:42

2020-05-28 08:29:54

目录脚本测试

2020-11-02 13:44:56

CentOSK8SLinux

2019-01-06 16:15:50

云计算SaaSIaaS

2009-05-06 17:20:53

密码认证SafeNetAladdin
点赞
收藏

51CTO技术栈公众号