初學GO,time包里sleep是最常用,今天突然看到一個time.after,特記錄time.after用法筆記如下:
首先是time包里的定義
// After waits for the duration to elapse and then sends the current time // on the returned channel. // It is equivalent to NewTimer(d).C. // The underlying Timer is not recovered by the garbage collector // until the timer fires. If efficiency is a concern, use NewTimer // instead and call Timer.Stop if the timer is no longer needed. func After(d Duration) <-chan Time { return NewTimer(d).C }
直譯就是:
等待參數duration時間后,向返回的chan里面寫入當前時間。
和NewTimer(d).C效果一樣
直到計時器觸發,垃圾回收器才會恢復基礎計時器。
如果擔心效率問題, 請改用 NewTimer, 然后調用計時器. 不用了就停止計時器。
解釋一下,是什么意思呢?
就是調用time.After(duration),此函數馬上返回,返回一個time.Time類型的Chan,不阻塞。
后面你該做什么做什么,不影響。到了duration時間后,自動塞一個當前時間進去。
你可以阻塞的等待,或者晚點再取。
因為底層是用NewTimer實現的,所以如果考慮到效率低,可以直接自己調用NewTimer。
package main import ( "time" "fmt" ) func main() { tchan := time.After(time.Second*3) fmt.Printf("tchan type=%T\n",tchan) fmt.Println("mark 1") fmt.Println("tchan=",<-tchan) fmt.Println("mark 2") }
上面的例子運行結果如下
tchan type=<-chan time.Time
mark 1
tchan= 2018-03-15 09:38:51.023106 +0800 CST m=+3.015805601
mark 2
首先瞬間打印出前兩行,然后等待3S,打印后后兩行。