溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

怎么使用go語(yǔ)言Timer計(jì)時(shí)器

發(fā)布時(shí)間:2020-07-23 11:11:43 來(lái)源:億速云 閱讀:254 作者:小豬 欄目:編程語(yǔ)言

這篇文章主要講解了怎么使用go語(yǔ)言Timer計(jì)時(shí)器,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。

計(jì)時(shí)器用來(lái)定時(shí)執(zhí)行任務(wù),分享一段代碼:

package main
import "time"
import "fmt"
func main() {
//新建計(jì)時(shí)器,兩秒以后觸發(fā),go觸發(fā)計(jì)時(shí)器的方法比較特別,就是在計(jì)時(shí)器的channel中發(fā)送值
timer1 := time.NewTimer(time.Second * 2)
//此處在等待channel中的信號(hào),執(zhí)行此段代碼時(shí)會(huì)阻塞兩秒
<-timer1.C
fmt.Println("Timer 1 expired")
//新建計(jì)時(shí)器,一秒后觸發(fā)
timer2 := time.NewTimer(time.Second)
//新開(kāi)啟一個(gè)線(xiàn)程來(lái)處理觸發(fā)后的事件
go func() {
//等觸發(fā)時(shí)的信號(hào)
<-timer2.C
fmt.Println("Timer 2 expired")
}()
//由于上面的等待信號(hào)是在新線(xiàn)程中,所以代碼會(huì)繼續(xù)往下執(zhí)行,停掉計(jì)時(shí)器
stop2 := timer2.Stop()
if stop2 {
fmt.Println("Timer 2 stopped")
}
}

代碼解讀見(jiàn)注釋。

最終輸出結(jié)果為:

Timer 1 expired

Timer 2 stopped

因?yàn)門(mén)imer 2的處理線(xiàn)程在等到信號(hào)前已經(jīng)被停止掉了,所以會(huì)打印出Timer 2 stopped而不是Timer 2 expired

附錄:下面看下Go語(yǔ)言計(jì)時(shí)器的使用詳解

Go語(yǔ)言計(jì)時(shí)器

Go語(yǔ)言的標(biāo)準(zhǔn)庫(kù)里提供兩種類(lèi)型的計(jì)時(shí)器TimerTicker。Timer經(jīng)過(guò)指定的duration時(shí)間后被觸發(fā),往自己的時(shí)間channel發(fā)送當(dāng)前時(shí)間,此后Timer不再計(jì)時(shí)。Ticker則是每隔duration時(shí)間都會(huì)把當(dāng)前時(shí)間點(diǎn)發(fā)送給自己的時(shí)間channel,利用計(jì)時(shí)器的時(shí)間channel可以實(shí)現(xiàn)很多與計(jì)時(shí)相關(guān)的功能。

文章主要涉及如下內(nèi)容:

  • TimerTicker計(jì)時(shí)器的內(nèi)部結(jié)構(gòu)表示
  • TimerTicker的使用方法和注意事項(xiàng)
  • 如何正確Reset定時(shí)器

計(jì)時(shí)器的內(nèi)部表示

兩種計(jì)時(shí)器都是基于Go語(yǔ)言的運(yùn)行時(shí)計(jì)時(shí)器runtime.timer實(shí)現(xiàn)的,rumtime.timer的結(jié)構(gòu)體表示如下:

type timer struct {
 pp puintptr

 when int64
 period int64
 f func(interface{}, uintptr)
 arg interface{}
 seq uintptr
 nextwhen int64
 status uint32
}

rumtime.timer結(jié)構(gòu)體中的字段含義是

  • when— 當(dāng)前計(jì)時(shí)器被喚醒的時(shí)間;
  • period— 兩次被喚醒的間隔;
  • f— 每當(dāng)計(jì)時(shí)器被喚醒時(shí)都會(huì)調(diào)用的函數(shù);
  • arg— 計(jì)時(shí)器被喚醒時(shí)調(diào)用 f傳入的參數(shù);
  • nextWhen— 計(jì)時(shí)器處于 timerModifiedLater/timerModifiedEairlier狀態(tài)時(shí),用于設(shè)置 when字段;
  • status— 計(jì)時(shí)器的狀態(tài);

這里的runtime.timer只是私有的計(jì)時(shí)器運(yùn)行時(shí)表示,對(duì)外暴露的計(jì)時(shí)器 time.Timertime.Ticker的結(jié)構(gòu)體表示如下:

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

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

Timer.CTicker.C就是計(jì)時(shí)器中的時(shí)間channel,接下來(lái)我們看一下怎么使用這兩種計(jì)時(shí)器,以及使用時(shí)要注意的地方。

Timer計(jì)時(shí)器

time.Timer計(jì)時(shí)器必須通過(guò) time.NewTimer、time.AfterFunc或者 time.After函數(shù)創(chuàng)建。當(dāng)計(jì)時(shí)器失效時(shí),失效的時(shí)間就會(huì)被發(fā)送給計(jì)時(shí)器持有的 channel,訂閱 channel的 goroutine會(huì)收到計(jì)時(shí)器失效的時(shí)間。

通過(guò)定時(shí)器Timer用戶(hù)可以定義自己的超時(shí)邏輯,尤其是在應(yīng)對(duì)使用select處理多個(gè)channel的超時(shí)、單channel讀寫(xiě)的超時(shí)等情形時(shí)尤為方便。Timer常見(jiàn)的使用方法如下:

//使用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,在到達(dá)超時(shí)時(shí)間后會(huì)在單獨(dú)的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ù)并非直接賦值給了運(yùn)行時(shí)計(jì)時(shí)器的f,而是作為包裝函數(shù)goFunc的參數(shù)傳入的。goFunc會(huì)啟動(dòng)了一個(gè)新的goroutine來(lái)執(zhí)行外部傳入的函數(shù)f。這是因?yàn)樗杏?jì)時(shí)器的事件函數(shù)都是由Go運(yùn)行時(shí)內(nèi)唯一的goroutinetimerproc運(yùn)行的。為了不阻塞timerproc的執(zhí)行,必須啟動(dòng)一個(gè)新的goroutine執(zhí)行到期的事件函數(shù)。

對(duì)于NewTimerAfter這兩種創(chuàng)建方法,則是Timer在超時(shí)后,執(zhí)行一個(gè)標(biāo)準(zhǔn)庫(kù)中內(nèi)置的函數(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將當(dāng)前時(shí)間發(fā)送到Timer的時(shí)間channel中。那么這個(gè)動(dòng)作不會(huì)阻塞timerproc的執(zhí)行么?答案是不會(huì),原因是NewTimer創(chuàng)建的是一個(gè)帶緩沖的channel所以無(wú)論Timer.C這個(gè)channel有沒(méi)有接收方sendTime都可以非阻塞的將當(dāng)前時(shí)間發(fā)送給Timer.C,而且sendTime中還加了雙保險(xiǎn):通過(guò)select判斷Timer.CBuffer是否已滿(mǎn),一旦滿(mǎn)了,會(huì)直接退出,依然不會(huì)阻塞。

TimerStop方法可以阻止計(jì)時(shí)器觸發(fā),調(diào)用Stop方法成功停止了計(jì)時(shí)器的觸發(fā)將會(huì)返回true,如果計(jì)時(shí)器已經(jīng)過(guò)期了或者已經(jīng)被Stop停止過(guò)了,再次調(diào)用Stop方法將會(huì)返回false。

Go運(yùn)行時(shí)將所有計(jì)時(shí)器維護(hù)在一個(gè)最小堆Min Heap中,Stop一個(gè)計(jì)時(shí)器就是從堆中刪除該計(jì)時(shí)器。

Ticker計(jì)時(shí)器

Ticker可以周期性地觸發(fā)時(shí)間事件,每次到達(dá)指定的時(shí)間間隔后都會(huì)觸發(fā)事件。

time.Ticker需要通過(guò)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")

不過(guò)time.Tick很少會(huì)被用到,除非你想在程序的整個(gè)生命周期里都使用time.Ticker的時(shí)間channel。官文文檔里對(duì)time.Tick的描述是:

time.Tick底層的Ticker不能被垃圾收集器恢復(fù);

所以使用time.Tick時(shí)一定要小心,為避免意外盡量使用time.NewTicker返回的Ticker替代。

NewTicker創(chuàng)建的計(jì)時(shí)器與NewTimer創(chuàng)建的計(jì)時(shí)器持有的時(shí)間channel一樣都是帶一個(gè)緩存的channel,每次觸發(fā)后執(zhí)行的函數(shù)也是sendTime,這樣即保證了無(wú)論有誤接收方Ticker觸發(fā)時(shí)間事件時(shí)都不會(huì)阻塞:

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計(jì)時(shí)器時(shí)要注意的問(wèn)題

關(guān)于Reset的使用建議,文檔里的描述是:

重置計(jì)時(shí)器時(shí)必須注意不要與當(dāng)前計(jì)時(shí)器到期發(fā)送時(shí)間到t.C的操作產(chǎn)生競(jìng)爭(zhēng)。如果程序已經(jīng)從t.C接收到值,則計(jì)時(shí)器是已知的已過(guò)期,并且t.Reset可以直接使用。如果程序尚未從t.C接收值,計(jì)時(shí)器必須先被停止,并且-如果使用t.Stop時(shí)報(bào)告計(jì)時(shí)器已過(guò)期,那么請(qǐng)排空其通道中值。

例如:

if !t.Stop() {
 <-t.C
}
t.Reset(d)

下面的例子里producer goroutine里每一秒向通道中發(fā)送一個(gè)false值,循環(huán)結(jié)束后等待一秒再往通道里發(fā)送一個(gè)true值。在consumer goroutine里通過(guò)循環(huán)試圖從通道中讀取值,用計(jì)時(shí)器設(shè)置了最長(zhǎng)等待時(shí)間為5秒,如果計(jì)時(shí)器超時(shí)了,輸出當(dāng)前時(shí)間并進(jìn)行下次循環(huán)嘗試,如果從通道中讀取出的不是期待的值(預(yù)期值是true),則嘗試重新從通道中讀取并重置計(jì)時(shí)器。

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

目前來(lái)看沒(méi)什么問(wèn)題,使用Reset重置計(jì)時(shí)器也起作用了,接下來(lái)我們對(duì)producer goroutin做一些更改,我們把producer goroutine里每秒發(fā)送值的邏輯改成每6秒發(fā)送值,而consumer gouroutine里和計(jì)時(shí)器還是5秒就到期。

// producer
 go func() {
 for i := 0; i < 5; i++ {
  time.Sleep(time.Second * 6)
  c <- false
 }

 time.Sleep(time.Second * 6)
 c <- true
 }()

再次運(yùn)行會(huì)發(fā)現(xiàn)程序發(fā)生了deadlock在第一次報(bào)告計(jì)時(shí)器過(guò)期后直接阻塞住了:

2020-05-13 13:09:11.166976 +0800 CST m=+5.005266022 :timer expired

那程序是在哪阻塞住的呢?對(duì)就是在抽干timer.C通道時(shí)阻塞住了(英文叫做drain channel比喻成流干管道里的水,在程序里就是讓timer.C管道中不再存在未接收的值)。

producer goroutine的發(fā)送行為發(fā)生了變化,comsumer goroutine在收到第一個(gè)數(shù)據(jù)前有了一次計(jì)時(shí)器過(guò)期的事件,for循環(huán)進(jìn)行一下次循環(huán)。這時(shí)timer.Stop函數(shù)返回的不再是true,而是false,因?yàn)橛?jì)時(shí)器已經(jīng)過(guò)期了,上面提到的維護(hù)著所有活躍計(jì)時(shí)器的最小堆中已經(jīng)不包含該計(jì)時(shí)器了。而此時(shí)timer.C中并沒(méi)有數(shù)據(jù),接下來(lái)用于drain channel的代碼會(huì)將consumer goroutine阻塞住。

這種情況,我們應(yīng)該直接Reset計(jì)時(shí)器,而不用顯式drain channel。如何將這兩種情形合二為一呢?我們可以利用一個(gè)select來(lái)包裹drain channel的操作,這樣無(wú)論channel中是否有數(shù)據(jù),drain都不會(huì)阻塞住。

//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
  }
 }
 }()

運(yùn)行修改后的程序,發(fā)現(xiàn)程序不會(huì)被阻塞住,能正常進(jìn)行通道讀取,讀取到true值后會(huì)自行退出。輸出結(jié)果如下:

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

總結(jié)

以上比較詳細(xì)地介紹了Go語(yǔ)言的計(jì)時(shí)器以及它們的使用方法和注意事項(xiàng),總結(jié)一下有如下關(guān)鍵點(diǎn):

  • TimerTicker都是在運(yùn)行時(shí)計(jì)時(shí)器runtime.timer的基礎(chǔ)上實(shí)現(xiàn)的。
  • 運(yùn)行時(shí)里的所有計(jì)時(shí)器都由運(yùn)行時(shí)內(nèi)唯一的timerproc觸發(fā)。
  • time.Tick創(chuàng)建的Ticker在運(yùn)行時(shí)不會(huì)被gc回收,能不用就不用。
  • TimerTicker的時(shí)間channel都是帶有一個(gè)緩沖的通道。
  • time.Aftertime.NewTimer,time.NewTicker創(chuàng)建的計(jì)時(shí)器觸發(fā)時(shí)都會(huì)執(zhí)行sendTime。
  • sendTime和計(jì)時(shí)器帶緩沖的時(shí)間通道保證了計(jì)時(shí)器不會(huì)阻塞程序。
  • Reset計(jì)時(shí)器時(shí)要注意drain channel和計(jì)時(shí)器過(guò)期存在競(jìng)爭(zhēng)條件。

看完上述內(nèi)容,是不是對(duì)怎么使用go語(yǔ)言Timer計(jì)時(shí)器有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI