這篇文章主要講解了如何使用Go語(yǔ)言的計(jì)時(shí)器,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。
創(chuàng)新互聯(lián)總部坐落于成都市區(qū),致力網(wǎng)站建設(shè)服務(wù)有成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作、網(wǎng)絡(luò)營(yíng)銷策劃、網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站維護(hù)、公眾號(hào)搭建、微信小程序開發(fā)、軟件開發(fā)等為企業(yè)提供一整套的信息化建設(shè)解決方案。創(chuàng)造真正意義上的網(wǎng)站建設(shè),為互聯(lián)網(wǎng)品牌在互動(dòng)行銷領(lǐng)域創(chuàng)造價(jià)值而不懈努力!
Go
語(yǔ)言的標(biāo)準(zhǔn)庫(kù)里提供兩種類型的計(jì)時(shí)器Timer
和Ticker
。Timer
經(jīng)過指定的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)容:
Timer
和Ticker
計(jì)時(shí)器的內(nèi)部結(jié)構(gòu)表示Timer
和Ticker
的使用方法和注意事項(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)體中的字段含義是
這里的 runtime.timer 只是私有的計(jì)時(shí)器運(yùn)行時(shí)表示,對(duì)外暴露的計(jì)時(shí)器 time.Timer 和time.Ticker的結(jié)構(gòu)體表示如下:
type Timer struct { C <-chan Time r runtimeTimer } type Ticker struct { C <-chan Time r runtimeTimer }
Timer.C和Ticker.C就是計(jì)時(shí)器中的時(shí)間channel,接下來我們看一下怎么使用這兩種計(jì)時(shí)器,以及使用時(shí)要注意的地方。
Timer計(jì)時(shí)器
time.Timer 計(jì)時(shí)器必須通過 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í)間。
通過定時(shí)器Timer用戶可以定義自己的超時(shí)邏輯,尤其是在應(yīng)對(duì)使用select處理多個(gè)channel的超時(shí)、單channel讀寫的超時(shí)等情形時(shí)尤為方便。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,在到達(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)魅氲膄參數(shù)并非直接賦值給了運(yùn)行時(shí)計(jì)時(shí)器的f,而是作為包裝函數(shù)goFunc的參數(shù)傳入的。goFunc會(huì)啟動(dòng)了一個(gè)新的goroutine來執(zhí)行外部傳入的函數(shù)f。這是因?yàn)樗杏?jì)時(shí)器的事件函數(shù)都是由Go運(yùn)行時(shí)內(nèi)唯一的 goroutine timerproc運(yùn)行的。為了不阻塞timerproc的執(zhí)行,必須啟動(dòng)一個(gè)新的goroutine執(zhí)行到期的事件函數(shù)。
對(duì)于NewTimer和After這兩種創(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有沒有接收方sendTime都可以非阻塞的將當(dāng)前時(shí)間發(fā)送給Timer.C,而且sendTime中還加了雙保險(xiǎn):通過select判斷Timer.C的Buffer是否已滿,一旦滿了,會(huì)直接退出,依然不會(huì)阻塞。
Timer的Stop方法可以阻止計(jì)時(shí)器觸發(fā),調(diào)用Stop方法成功停止了計(jì)時(shí)器的觸發(fā)將會(huì)返回true,如果計(jì)時(shí)器已經(jīng)過期了或者已經(jīng)被Stop停止過了,再次調(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需要通過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很少會(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í)要注意的問題
關(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í)器是已知的已過期,并且t.Reset可以直接使用。如果程序尚未從t.C接收值,計(jì)時(shí)器必須先被停止,并且-如果使用t.Stop時(shí)報(bào)告計(jì)時(shí)器已過期,那么請(qǐng)排空其通道中值。
例如:
if !t.Stop() { <-t.C } t.Reset(d)
下面的例子里producer goroutine里每一秒向通道中發(fā)送一個(gè)false值,循環(huán)結(jié)束后等待一秒再往通道里發(fā)送一個(gè)true值。在consumer goroutine里通過循環(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
目前來看沒什么問題,使用Reset重置計(jì)時(shí)器也起作用了,接下來我們對(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í)器過期后直接阻塞住了:
2020-05-13 13:09:11.166976 +0800 CST m=+5.005266022 :timer expired
那程序是在哪阻塞住的呢?對(duì)就是在抽干timer.C通道時(shí)阻塞住了(英文叫做drain channel比喻成流干管道里的水,在程序里就是讓timer.C管道中不再存在未接收的值)。
if !timer.Stop() { <-timer.C } timer.Reset(time.Second * 5)
producer goroutine的發(fā)送行為發(fā)生了變化,comsumer goroutine在收到第一個(gè)數(shù)據(jù)前有了一次計(jì)時(shí)器過期的事件,for循環(huán)進(jìn)行一下次循環(huán)。這時(shí)timer.Stop函數(shù)返回的不再是true,而是false,因?yàn)橛?jì)時(shí)器已經(jīng)過期了,上面提到的維護(hù)著所有活躍計(jì)時(shí)器的最小堆中已經(jīng)不包含該計(jì)時(shí)器了。而此時(shí)timer.C中并沒有數(shù)據(jù),接下來用于drain channel的代碼會(huì)將consumer goroutine阻塞住。
這種情況,我們應(yīng)該直接Reset計(jì)時(shí)器,而不用顯式drain channel。如何將這兩種情形合二為一呢?我們可以利用一個(gè)select來包裹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):
看完上述內(nèi)容,是不是對(duì)如何使用Go語(yǔ)言的計(jì)時(shí)器有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
本文名稱:如何使用Go語(yǔ)言的計(jì)時(shí)器
當(dāng)前鏈接:http://aaarwkj.com/article2/iijhoc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供建站公司、網(wǎng)站營(yíng)銷、關(guān)鍵詞優(yōu)化、全網(wǎng)營(yíng)銷推廣、Google、響應(yīng)式網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)