計時器用來定時執行任務,分享一段代碼:
package main import "time" import "fmt" func main() { //新建計時器,兩秒以后觸發,go觸發計時器的方法比較特別,就是在計時器的channel中發送值 timer1 := time.NewTimer(time.Second * 2) //此處在等待channel中的信號,執行此段代碼時會阻塞兩秒 <-timer1.C fmt.Println("Timer 1 expired") //新建計時器,一秒后觸發 timer2 := time.NewTimer(time.Second) //新開啟一個線程來處理觸發后的事件 go func() { //等觸發時的信號 <-timer2.C fmt.Println("Timer 2 expired") }() //由於上面的等待信號是在新線程中,所以代碼會繼續往下執行,停掉計時器 stop2 := timer2.Stop() if stop2 { fmt.Println("Timer 2 stopped") } }
代碼解讀見注釋。
最終輸出結果為:
Timer 1 expired
Timer 2 stopped
因為Timer 2的處理線程在等到信號前已經被停止掉了,所以會打印出Timer 2 stopped而不是Timer 2 expired