計時器用來定時執(zhí)行任務,分享一段代碼:
package main
import "time"
import "fmt"
func main() {
//新建計時器,兩秒以后觸發(fā),go觸發(fā)計時器的方法比較特別,就是在計時器的channel中發(fā)送值
timer1 := time.NewTimer(time.Second * 2)
//此處在等待channel中的信號,執(zhí)行此段代碼時會阻塞兩秒
-timer1.C
fmt.Println("Timer 1 expired")
//新建計時器,一秒后觸發(fā)
timer2 := time.NewTimer(time.Second)
//新開啟一個線程來處理觸發(fā)后的事件
go func() {
//等觸發(fā)時的信號
-timer2.C
fmt.Println("Timer 2 expired")
}()
//由于上面的等待信號是在新線程中,所以代碼會繼續(xù)往下執(zhí)行,停掉計時器
stop2 := timer2.Stop()
if stop2 {
fmt.Println("Timer 2 stopped")
}
}
代碼解讀見注釋。
最終輸出結果為:
Timer 1 expired
Timer 2 stopped
因為Timer 2的處理線程在等到信號前已經被停止掉了,所以會打印出Timer 2 stopped而不是Timer 2 expired
附錄:下面看下Go語言計時器的使用詳解
Go語言計時器
Go
語言的標準庫里提供兩種類型的計時器Timer
和Ticker
。Timer
經過指定的duration
時間后被觸發(fā),往自己的時間channel
發(fā)送當前時間,此后Timer
不再計時。Ticker
則是每隔duration
時間都會把當前時間點發(fā)送給自己的時間channel
,利用計時器的時間channel
可以實現(xiàn)很多與計時相關的功能。
文章主要涉及如下內容:
Timer
和Ticker
計時器的內部結構表示
Timer
和Ticker
的使用方法和注意事項
- 如何正確
Reset
定時器
計時器的內部表示
兩種計時器都是基于Go
語言的運行時計時器runtime.timer
實現(xiàn)的,rumtime.timer
的結構體表示如下:
type timer struct {
pp puintptr
when int64
period int64
f func(interface{}, uintptr)
arg interface{}
seq uintptr
nextwhen int64
status uint32
}
rumtime.timer
結構體中的字段含義是
when
— 當前計時器被喚醒的時間;
period
— 兩次被喚醒的間隔;
f
— 每當計時器被喚醒時都會調用的函數(shù);
arg
— 計時器被喚醒時調用 f
傳入的參數(shù);
nextWhen
— 計時器處于 timerModifiedLater/timerModifiedEairlier
狀態(tài)時,用于設置 when
字段;
status
— 計時器的狀態(tài);
這里的runtime.timer
只是私有的計時器運行時表示,對外暴露的計時器 time.Timer
和time.Ticker
的結構體表示如下:
type Timer struct {
C -chan Time
r runtimeTimer
}
type Ticker struct {
C -chan Time
r runtimeTimer
}
Timer.C
和Ticker.C
就是計時器中的時間channel
,接下來我們看一下怎么使用這兩種計時器,以及使用時要注意的地方。
Timer計時器
time.Timer
計時器必須通過 time.NewTimer
、time.AfterFunc
或者 time.After
函數(shù)創(chuàng)建。當計時器失效時,失效的時間就會被發(fā)送給計時器持有的 channel
,訂閱 channel
的 goroutine
會收到計時器失效的時間。
通過定時器Timer
用戶可以定義自己的超時邏輯,尤其是在應對使用select
處理多個channel
的超時、單channel
讀寫的超時等情形時尤為方便。Timer
常見的使用方法如下:
//使用time.AfterFunc:
t := time.AfterFunc(d, f)
//使用time.After:
select {
case m := -c:
handle(m)
case -time.After(5 * time.Minute):
fmt.Println("timed out")
}
// 使用time.NewTimer:
t := time.NewTimer(5 * time.Minute)
select {
case m := -c:
handle(m)
case -t.C:
fmt.Println("timed out")
}
time.AfterFunc
這種方式創(chuàng)建的Timer
,在到達超時時間后會在單獨的goroutine
里執(zhí)行函數(shù)f
。
func AfterFunc(d Duration, f func()) *Timer {
t := Timer{
r: runtimeTimer{
when: when(d),
f: goFunc,
arg: f,
},
}
startTimer(t.r)
return t
}
func goFunc(arg interface{}, seq uintptr) {
go arg.(func())()
}
從上面AfterFunc
的源碼可以看到外面?zhèn)魅氲?code>f參數(shù)并非直接賦值給了運行時計時器的f
,而是作為包裝函數(shù)goFunc
的參數(shù)傳入的。goFunc
會啟動了一個新的goroutine
來執(zhí)行外部傳入的函數(shù)f
。這是因為所有計時器的事件函數(shù)都是由Go
運行時內唯一的goroutine
timerproc
運行的。為了不阻塞timerproc
的執(zhí)行,必須啟動一個新的goroutine
執(zhí)行到期的事件函數(shù)。
對于NewTimer
和After
這兩種創(chuàng)建方法,則是Timer
在超時后,執(zhí)行一個標準庫中內置的函數(shù):sendTime
。
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 sendTime(c interface{}, seq uintptr) {
select {
case c.(chan Time) - Now():
default:
}
}
sendTime
將當前時間發(fā)送到Timer
的時間channel
中。那么這個動作不會阻塞timerproc
的執(zhí)行么?答案是不會,原因是NewTimer
創(chuàng)建的是一個帶緩沖的channel
所以無論Timer.C
這個channel
有沒有接收方sendTime
都可以非阻塞的將當前時間發(fā)送給Timer.C
,而且sendTime
中還加了雙保險:通過select
判斷Timer.C
的Buffer
是否已滿,一旦滿了,會直接退出,依然不會阻塞。
Timer
的Stop
方法可以阻止計時器觸發(fā),調用Stop
方法成功停止了計時器的觸發(fā)將會返回true
,如果計時器已經過期了或者已經被Stop
停止過了,再次調用Stop
方法將會返回false
。
Go
運行時將所有計時器維護在一個最小堆Min Heap
中,Stop
一個計時器就是從堆中刪除該計時器。
Ticker計時器
Ticker
可以周期性地觸發(fā)時間事件,每次到達指定的時間間隔后都會觸發(fā)事件。
time.Ticker
需要通過time.NewTicker
或者time.Tick
創(chuàng)建。
// 使用time.Tick:
go func() {
for t := range time.Tick(time.Minute) {
fmt.Println("Tick at", t)
}
}()
// 使用time.Ticker
var ticker *time.Ticker = time.NewTicker(1 * time.Second)
go func() {
for t := range ticker.C {
fmt.Println("Tick at", t)
}
}()
time.Sleep(time.Second * 5)
ticker.Stop()
fmt.Println("Ticker stopped")
不過time.Tick
很少會被用到,除非你想在程序的整個生命周期里都使用time.Ticker
的時間channel
。官文文檔里對time.Tick
的描述是:
time.Tick
底層的Ticker
不能被垃圾收集器恢復;
所以使用time.Tick
時一定要小心,為避免意外盡量使用time.NewTicker
返回的Ticker
替代。
NewTicker
創(chuàng)建的計時器與NewTimer
創(chuàng)建的計時器持有的時間channel
一樣都是帶一個緩存的channel
,每次觸發(fā)后執(zhí)行的函數(shù)也是sendTime
,這樣即保證了無論有誤接收方Ticker
觸發(fā)時間事件時都不會阻塞:
func NewTicker(d Duration) *Ticker {
if d = 0 {
panic(errors.New("non-positive interval for NewTicker"))
}
// Give the channel a 1-element time buffer.
// If the client falls behind while reading, we drop ticks
// on the floor until the client catches up.
c := make(chan Time, 1)
t := Ticker{
C: c,
r: runtimeTimer{
when: when(d),
period: int64(d),
f: sendTime,
arg: c,
},
}
startTimer(t.r)
return t
}
Reset計時器時要注意的問題
關于Reset
的使用建議,文檔里的描述是:
重置計時器時必須注意不要與當前計時器到期發(fā)送時間到t.C的操作產生競爭。如果程序已經從t.C接收到值,則計時器是已知的已過期,并且t.Reset可以直接使用。如果程序尚未從t.C接收值,計時器必須先被停止,并且-如果使用t.Stop時報告計時器已過期,那么請排空其通道中值。
例如:
if !t.Stop() {
-t.C
}
t.Reset(d)
下面的例子里producer goroutine
里每一秒向通道中發(fā)送一個false
值,循環(huán)結束后等待一秒再往通道里發(fā)送一個true
值。在consumer goroutine
里通過循環(huán)試圖從通道中讀取值,用計時器設置了最長等待時間為5秒,如果計時器超時了,輸出當前時間并進行下次循環(huán)嘗試,如果從通道中讀取出的不是期待的值(預期值是true
),則嘗試重新從通道中讀取并重置計時器。
func main() {
c := make(chan bool)
go func() {
for i := 0; i 5; i++ {
time.Sleep(time.Second * 1)
c - false
}
time.Sleep(time.Second * 1)
c - true
}()
go func() {
// try to read from channel, block at most 5s.
// if timeout, print time event and go on loop.
// if read a message which is not the type we want(we want true, not false),
// retry to read.
timer := time.NewTimer(time.Second * 5)
for {
// timer is active , not fired, stop always returns true, no problems occurs.
if !timer.Stop() {
-timer.C
}
timer.Reset(time.Second * 5)
select {
case b := -c:
if b == false {
fmt.Println(time.Now(), ":recv false. continue")
continue
}
//we want true, not false
fmt.Println(time.Now(), ":recv true. return")
return
case -timer.C:
fmt.Println(time.Now(), ":timer expired")
continue
}
}
}()
//to avoid that all goroutine blocks.
var s string
fmt.Scanln(s)
}
程序的輸出如下:
2020-05-13 12:49:48.90292 +0800 CST m=+1.004554120 :recv false. continue
2020-05-13 12:49:49.906087 +0800 CST m=+2.007748042 :recv false. continue
2020-05-13 12:49:50.910208 +0800 CST m=+3.011892138 :recv false. continue
2020-05-13 12:49:51.914291 +0800 CST m=+4.015997373 :recv false. continue
2020-05-13 12:49:52.916762 +0800 CST m=+5.018489240 :recv false. continue
2020-05-13 12:49:53.920384 +0800 CST m=+6.022129708 :recv true. return
目前來看沒什么問題,使用Reset重置計時器也起作用了,接下來我們對producer goroutin
做一些更改,我們把producer goroutine
里每秒發(fā)送值的邏輯改成每6
秒發(fā)送值,而consumer gouroutine
里和計時器還是5
秒就到期。
// producer
go func() {
for i := 0; i 5; i++ {
time.Sleep(time.Second * 6)
c - false
}
time.Sleep(time.Second * 6)
c - true
}()
再次運行會發(fā)現(xiàn)程序發(fā)生了deadlock
在第一次報告計時器過期后直接阻塞住了:
2020-05-13 13:09:11.166976 +0800 CST m=+5.005266022 :timer expired
那程序是在哪阻塞住的呢?對就是在抽干timer.C
通道時阻塞住了(英文叫做drain channel比喻成流干管道里的水,在程序里就是讓timer.C
管道中不再存在未接收的值)。
producer goroutine
的發(fā)送行為發(fā)生了變化,comsumer goroutine
在收到第一個數(shù)據前有了一次計時器過期的事件,for
循環(huán)進行一下次循環(huán)。這時timer.Stop
函數(shù)返回的不再是true
,而是false
,因為計時器已經過期了,上面提到的維護著所有活躍計時器的最小堆中已經不包含該計時器了。而此時timer.C
中并沒有數(shù)據,接下來用于drain channel
的代碼會將consumer goroutine
阻塞住。
這種情況,我們應該直接Reset
計時器,而不用顯式drain channel
。如何將這兩種情形合二為一呢?我們可以利用一個select
來包裹drain channel
的操作,這樣無論channel
中是否有數(shù)據,drain
都不會阻塞住。
//consumer
go func() {
// try to read from channel, block at most 5s.
// if timeout, print time event and go on loop.
// if read a message which is not the type we want(we want true, not false),
// retry to read.
timer := time.NewTimer(time.Second * 5)
for {
// timer may be not active, and fired
if !timer.Stop() {
select {
case -timer.C: //try to drain from the channel
default:
}
}
timer.Reset(time.Second * 5)
select {
case b := -c:
if b == false {
fmt.Println(time.Now(), ":recv false. continue")
continue
}
//we want true, not false
fmt.Println(time.Now(), ":recv true. return")
return
case -timer.C:
fmt.Println(time.Now(), ":timer expired")
continue
}
}
}()
運行修改后的程序,發(fā)現(xiàn)程序不會被阻塞住,能正常進行通道讀取,讀取到true
值后會自行退出。輸出結果如下:
2020-05-13 13:25:08.412679 +0800 CST m=+5.005475546 :timer expired
2020-05-13 13:25:09.409249 +0800 CST m=+6.002037341 :recv false. continue
2020-05-13 13:25:14.412282 +0800 CST m=+11.005029547 :timer expired
2020-05-13 13:25:15.414482 +0800 CST m=+12.007221569 :recv false. continue
2020-05-13 13:25:20.416826 +0800 CST m=+17.009524859 :timer expired
2020-05-13 13:25:21.418555 +0800 CST m=+18.011245687 :recv false. continue
2020-05-13 13:25:26.42388 +0800 CST m=+23.016530193 :timer expired
2020-05-13 13:25:27.42294 +0800 CST m=+24.015582511 :recv false. continue
2020-05-13 13:25:32.425666 +0800 CST m=+29.018267054 :timer expired
2020-05-13 13:25:33.428189 +0800 CST m=+30.020782483 :recv false. continue
2020-05-13 13:25:38.432428 +0800 CST m=+35.024980796 :timer expired
2020-05-13 13:25:39.428343 +0800 CST m=+36.020887629 :recv true. return
總結
以上比較詳細地介紹了Go
語言的計時器以及它們的使用方法和注意事項,總結一下有如下關鍵點:
Timer
和Ticker
都是在運行時計時器runtime.timer
的基礎上實現(xiàn)的。
- 運行時里的所有計時器都由運行時內唯一的
timerproc
觸發(fā)。
time.Tick
創(chuàng)建的Ticker
在運行時不會被gc
回收,能不用就不用。
Timer
和Ticker
的時間channel
都是帶有一個緩沖的通道。
time.After
,time.NewTimer
,time.NewTicker
創(chuàng)建的計時器觸發(fā)時都會執(zhí)行sendTime
。
sendTime
和計時器帶緩沖的時間通道保證了計時器不會阻塞程序。
Reset
計時器時要注意drain channel
和計時器過期存在競爭條件。
到此這篇關于詳解Go 語言計時器的使用的文章就介紹到這了,更多相關go 語言計時器內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- Golang 定時器(Timer 和 Ticker),這篇文章就夠了
- go語言中使用timer的常用方式
- Go timer如何調度