Go
語言的標準庫里提供兩種類型的計時器Timer
和Ticker
。Timer
經過指定的duration
時間后被觸發,往自己的時間channel
發送當前時間,此后Timer
不再計時。Ticker
則是每隔duration
時間都會把當前時間點發送給自己的時間channel
,利用計時器的時間channel
可以實現很多與計時相關的功能。
文章主要涉及如下內容:
Timer
和Ticker
計時器的內部結構表示
Timer
和Ticker
的使用方法和注意事項
- 如何正確
Reset
定時器
計時器的內部表示
兩種計時器都是基于Go
語言的運行時計時器runtime.timer
實現的,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 — 每當計時器被喚醒時都會調用的函數;
- arg — 計時器被喚醒時調用 f 傳入的參數;
- nextWhen — 計時器處于 timerModifiedLater/timerModifiedEairlier 狀態時,用于設置 when 字段;
- status — 計時器的狀態;
這里的 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 函數創建。 當計時器失效時,失效的時間就會被發送給計時器持有的 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這種方式創建的Timer,在到達超時時間后會在單獨的goroutine里執行函數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的源碼可以看到外面傳入的f參數并非直接賦值給了運行時計時器的f,而是作為包裝函數goFunc的參數傳入的。goFunc會啟動了一個新的goroutine來執行外部傳入的函數f。這是因為所有計時器的事件函數都是由Go運行時內唯一的 goroutine timerproc運行的。為了不阻塞timerproc的執行,必須啟動一個新的goroutine執行到期的事件函數。
對于NewTimer和After這兩種創建方法,則是Timer在超時后,執行一個標準庫中內置的函數: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將當前時間發送到Timer的時間channel中。那么這個動作不會阻塞timerproc的執行么?答案是不會,原因是NewTimer創建的是一個帶緩沖的channel所以無論Timer.C這個channel有沒有接收方sendTime都可以非阻塞的將當前時間發送給Timer.C,而且sendTime中還加了雙保險:通過select判斷Timer.C的Buffer是否已滿,一旦滿了,會直接退出,依然不會阻塞。
Timer的Stop方法可以阻止計時器觸發,調用Stop方法成功停止了計時器的觸發將會返回true,如果計時器已經過期了或者已經被Stop停止過了,再次調用Stop方法將會返回false。
Go運行時將所有計時器維護在一個最小堆Min Heap中,Stop一個計時器就是從堆中刪除該計時器。
Ticker計時器
Ticker可以周期性地觸發時間事件,每次到達指定的時間間隔后都會觸發事件。
time.Ticker需要通過time.NewTicker或者time.Tick創建。
// 使用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創建的計時器與NewTimer創建的計時器持有的時間channel一樣都是帶一個緩存的channel,每次觸發后執行的函數也是sendTime,這樣即保證了無論有誤接收方Ticker觸發時間事件時都不會阻塞:
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的使用建議,文檔里的描述是:
重置計時器時必須注意不要與當前計時器到期發送時間到t.C的操作產生競爭。如果程序已經從t.C接收到值,則計時器是已知的已過期,并且t.Reset可以直接使用。如果程序尚未從t.C接收值,計時器必須先被停止,并且-如果使用t.Stop時報告計時器已過期,那么請排空其通道中值。
例如:
if !t.Stop() {
-t.C
}
t.Reset(d)
下面的例子里producer goroutine里每一秒向通道中發送一個false值,循環結束后等待一秒再往通道里發送一個true值。在consumer goroutine里通過循環試圖從通道中讀取值,用計時器設置了最長等待時間為5秒,如果計時器超時了,輸出當前時間并進行下次循環嘗試,如果從通道中讀取出的不是期待的值(預期值是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里每秒發送值的邏輯改成每6秒發送值,而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
}()
再次運行會發現程序發生了deadlock在第一次報告計時器過期后直接阻塞住了:
2020-05-13 13:09:11.166976 +0800 CST m=+5.005266022 :timer expired
那程序是在哪阻塞住的呢?對就是在抽干timer.C通道時阻塞住了(英文叫做drain channel比喻成流干管道里的水,在程序里就是讓timer.C管道中不再存在未接收的值)。
if !timer.Stop() {
-timer.C
}
timer.Reset(time.Second * 5)
producer goroutine的發送行為發生了變化,comsumer goroutine在收到第一個數據前有了一次計時器過期的事件,for循環進行一下次循環。這時timer.Stop函數返回的不再是true,而是false,因為計時器已經過期了,上面提到的維護著所有活躍計時器的最小堆中已經不包含該計時器了。而此時timer.C中并沒有數據,接下來用于drain channel的代碼會將consumer goroutine阻塞住。
這種情況,我們應該直接Reset計時器,而不用顯式drain channel。如何將這兩種情形合二為一呢?我們可以利用一個select來包裹drain channel的操作,這樣無論channel中是否有數據,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
}
}
}()
運行修改后的程序,發現程序不會被阻塞住,能正常進行通道讀取,讀取到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的基礎上實現的。
- 運行時里的所有計時器的事件函數都由運行時內唯一的goroutine timerproc觸發。
- time.Tick創建的Ticker在運行時不會被gc回收,能不用就不用。
- Timer和Ticker的時間channel都是帶有一個緩沖的通道。
- time.After,time.NewTimer,time.NewTicker創建的計時器觸發時都會執行sendTime。
- sendTime和計時器帶緩存的時間通道保證了計時器不會阻塞程序。
- Reset計時器時要注意drain channel和計時器過期存在競爭條件。
到此這篇關于Go語言的計時器的文章就介紹到這了,更多相關Go計時器內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!