go的timer定时器实现
生活随笔
收集整理的這篇文章主要介紹了
go的timer定时器实现
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
示例如下:
package mainimport ("fmt""time" )func testTimer1() {go func() {fmt.Println("test timer1")}()}func testTimer2() {go func() {fmt.Println(time.Now().String())}() }func timer1() {timer1 := time.NewTicker(1 * time.Second)for {select {case <-timer1.C:testTimer1()}} }func timer2() {timer2 := time.NewTicker(5 * time.Second)for {select {case <-timer2.C:testTimer2()}} }func main() {go timer1()timer2() }運(yùn)行結(jié)果截屏如下:
?
看go的time部分源碼?Ticker結(jié)構(gòu)?
type Ticker struct {C <-chan Time // The channel on which the ticks are delivered.r runtimeTimer}
go的time和ticket的調(diào)用
或者叫timmer internal和其他語言的開發(fā)思路不一樣。
其他語言,多是注冊回調(diào)函數(shù),定時(shí),時(shí)間到了調(diào)用回調(diào)。
go是 通過?chan
的阻塞實(shí)現(xiàn)的。
調(diào)用的地方,讀取chan?
定時(shí),時(shí)間到,向chan寫入值,阻塞解除,調(diào)用函數(shù)
?
轉(zhuǎn)載于:https://www.cnblogs.com/unqiang/p/6775617.html
總結(jié)
以上是生活随笔為你收集整理的go的timer定时器实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: u-boot nand flash re
- 下一篇: 关于用户空间和内核空间