Go内置的timer和ticker实现
1. 在未来某个时刻执行某段代码
2. 指定间隔周期性的执行某个任务
example/test1.go
package main
import (
"fmt"
"time"
)
func durationExec() {
timer := time.NewTicker(time.Second * 2)
<- timer.C
println("Timer expired")
}
func cancelExec() {
timer := time.NewTimer(time.Second * 2)
go func () {
fmt.Println("goroutine start")
<- timer.C
fmt.Println("Timer expired")
}()
time.Sleep(1)
fmt.Println("goroutine stop start")
stop := timer.Stop()
fmt.Println("Timer cancelled:",stop)
}
func repeateIntervalExec() {
ticker := time.NewTicker(time.Millisecond * 500)
go func() {
for t := range ticker.C {
fmt.Println("Tick at:",t)
}
}()
time.Sleep(time.Millisecond * 1500)
ticker.Stop()
fmt.Println("Ticker stopped")
}
func hookExec() {
timeChan := time.NewTimer(time.Second).C
tickChan := time.NewTicker(time.Millisecond * 500).C
doneChan := make(chan bool)
go func() {
time.Sleep(time.Second * 2)
doneChan <- true
}()
for {
select {
case <- timeChan:
fmt.Println("Timer expired")
case <- tickChan:
fmt.Println("Ticker ticked")
case <- doneChan:
fmt.Println("Done")
return
}
}
}
func main() {
fmt.Println("\ntime example-1")
//实现延迟执行的效果
durationExec()
fmt.Println("\ntime example-2")
//取消timer
cancelExec()
fmt.Println("\ntime example-3")
//间隔周期性执行
repeateIntervalExec()
fmt.Println("\ntime example-4")
//与其他交互
hookExec()
}
output
# go run test1.go
time example-1
Timer expired
time example-2
goroutine start
goroutine stop start
Timer cancelled: true
time example-3
Tick at: 2018-03-11 00:42:06.752574836 +0800 CST m=+2.500685090
Tick at: 2018-03-11 00:42:07.252591072 +0800 CST m=+3.000701322
Ticker stopped
time example-4
Tick at: 2018-03-11 00:42:07.752586713 +0800 CST m=+3.500696965
Ticker ticked
Timer expired
Ticker ticked
Ticker ticked
Ticker ticked
Done
参考
https://mmcgrana.github.io/2012/09/go-by-example-timers-and-tickers.html