1. 程式人生 > 程式設計 >go語言Timer計時器的用法示例詳解

go語言Timer計時器的用法示例詳解

計時器用來定時執行任務,分享一段程式碼:

package main
import "time"
import "fmt"
func main() {
//新建計時器,兩秒以後觸發,go觸發計時器的方法比較特別,就是在計時器的channel中傳送值
timer1 := time.NewTimer(time.Second * 2)
//此處在等待channel中的訊號,執行此段程式碼時會阻塞兩秒
<-timer1.C
fmt.Println("Timer 1 expired")
//新建計時器,一秒後觸發
timer2 := time.NewTimer(time.Second)
//新開啟一個執行緒來處理觸發後的事件
go func() {
//等觸發時的訊號
<-timer2.C
fmt.Println("Timer 2 expired")
}()
//由於上面的等待訊號是在新執行緒中,所以程式碼會繼續往下執行,停掉計時器
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語言的標準庫裡提供兩種型別的計時器TimerTickerTimer經過指定的duration時間後被觸發,往自己的時間channel傳送當前時間,此後Timer不再計時。Ticker則是每隔duration時間都會把當前時間點發送給自己的時間channel,利用計時器的時間channel

可以實現很多與計時相關的功能。

文章主要涉及如下內容:

  • TimerTicker計時器的內部結構表示
  • TimerTicker的使用方法和注意事項
  • 如何正確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.Timertime.Ticker的結構體表示如下:

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

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

Timer.CTicker.C就是計時器中的時間channel,接下來我們看一下怎麼使用這兩種計時器,以及使用時要注意的地方。

Timer計時器

time.Timer計時器必須通過time.NewTimertime.AfterFunc或者time.After函式建立。當計時器失效時,失效的時間就會被髮送給計時器持有的channel,訂閱channelgoroutine會收到計時器失效的時間。

通過定時器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執行時內唯一的goroutinetimerproc執行的。為了不阻塞timerproc的執行,必須啟動一個新的goroutine執行到期的事件函式。

對於NewTimerAfter這兩種建立方法,則是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.CBuffer是否已滿,一旦滿了,會直接退出,依然不會阻塞。

TimerStop方法可以阻止計時器觸發,呼叫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,period: int64(d),}
 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管道中不再存在未接收的值)。

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,// 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(),":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語言的計時器以及它們的使用方法和注意事項,總結一下有如下關鍵點:

  • TimerTicker都是在執行時計時器runtime.timer的基礎上實現的。
  • 執行時裡的所有計時器都由執行時內唯一的timerproc觸發。
  • time.Tick建立的Ticker在執行時不會被gc回收,能不用就不用。
  • TimerTicker的時間channel都是帶有一個緩衝的通道。
  • time.Aftertime.NewTimertime.NewTicker建立的計時器觸發時都會執行sendTime
  • sendTime和計時器帶緩衝的時間通道保證了計時器不會阻塞程式。
  • Reset計時器時要注意drain channel和計時器過期存在競爭條件。

到此這篇關於詳解Go 語言計時器的使用的文章就介紹到這了,更多相關go 語言計時器內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!