Go-原始碼分析與tick實現定時任務
阿新 • • 發佈:2020-08-07
tick實現定時任務
-
示例程式碼
package main import ( "fmt" "math/rand" "time" ) // schedule task func tack(ticker <-chan time.Time) { // for 迴圈中不斷執行select for { var flag = 0 select { case <-ticker: flag += rand.Intn(1000) fmt.Printf("**********task<%d>**********\n", flag) default: time.Sleep(1) } } } // fake competitor func competitor() { for { fmt.Printf("competitor running...\n") // goroutine 是搶佔式的,必須顯式地讓出CPU資源去處理其它任務 time.Sleep(time.Millisecond) } } // runner func run() { // for {} time.Sleep(time.Second * 5) } func main() { // Tick 返回一個長度為1的channel ticker := time.Tick(time.Second * 2) go tack(ticker) go competitor() run() }
-
原始碼分析
// Tick is a convenience wrapper for NewTicker providing access to the ticking // channel only. While Tick is useful for clients that have no need to shut down // the Ticker, be aware that without a way to shut it down the underlying // Ticker cannot be recovered by the garbage collector; it "leaks". // Unlike NewTicker, Tick will return nil if d <= 0. func Tick(d Duration) <-chan Time { if d <= 0 { return nil } return NewTicker(d).C //