go的timer定时器实现
生活随笔
收集整理的這篇文章主要介紹了
go的timer定时器实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
示例如下:
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() }運行結果截屏如下:
?
看go的time部分源碼?Ticker結構?
type Ticker struct {C <-chan Time // The channel on which the ticks are delivered.r runtimeTimer}
go的time和ticket的調用
或者叫timmer internal和其他語言的開發思路不一樣。
其他語言,多是注冊回調函數,定時,時間到了調用回調。
go是 通過?chan
的阻塞實現的。
調用的地方,讀取chan?
定時,時間到,向chan寫入值,阻塞解除,調用函數
?
轉載于:https://www.cnblogs.com/unqiang/p/6775617.html
總結
以上是生活随笔為你收集整理的go的timer定时器实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: u-boot nand flash re
- 下一篇: 关于用户空间和内核空间