1. 程式人生 > 實用技巧 >Go-原始碼分析與tick實現定時任務

Go-原始碼分析與tick實現定時任務

tick實現定時任務

  1. 示例程式碼

    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()
    }
    
  2. 原始碼分析

    // 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		//