Golang的定时器 · 音视频/C++/k8s/Docker等等 学习笔记 · 看云
[TOC]
## 概述
golang有三种方式实现定时器:
1. ticker
2. timer
3. select
## Ticker
通过 time.NewTicker(d)的方式实现定时器
```golang
d := time.Duration(time.Second * 2)
t1 := time.NewTicker(d)
defer t1.Stop()
go func() {
for {
<- t1.C
fmt.Println("NewTicker...")
}
}()
```
## Timer
通过 time.NewTimer(d)的方式实现定时器
```golang
t2 := time.NewTimer(d)
defer t2.Stop()
go func() {
for {
<- t2.C
fmt.Println("NewTimer...")
}
}()
```
## select
通过select的方式实现定时器:
```golang
for {
select {
case <- time.After(d):
fmt.Println("select...")
}
}
```
## 三种定时器示例代码
```golang
package main
import (
"fmt"
"time"
)
func main() {
d := time.Duration(time.Second * 2)
t1 := time.NewTicker(d)
defer t1.Stop()
go func() {
for {
<- t1.C
fmt.Println("NewTicker...")
}
}()
t2 := time.NewTimer(d)
defer t2.Stop()
go func() {
for {
<- t2.C
fmt.Println("NewTimer...")
}
}()
for {
select {
case <- time.After(d):
fmt.Println("select...")
}
}
}
```