初学GO,time包里sleep是最经常使用,今天忽然看到一个time.after,特记录time.after用法笔记以下:函数
首先是time包里的定义ui
// 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 }
直译就是: spa
等待参数duration时间后,向返回的chan里面写入当前时间。blog
和NewTimer(d).C效果同样ci
直到计时器触发,垃圾回收器才会恢复基础计时器。it
若是担忧效率问题, 请改用 NewTimer, 而后调用计时器. 不用了就中止计时器。io
解释一下,是什么意思呢?class
就是调用time.After(duration),此函数立刻返回,返回一个time.Time类型的Chan,不阻塞。效率
后面你该作什么作什么,不影响。到了duration时间后,自动塞一个当前时间进去。import
你能够阻塞的等待,或者晚点再取。
由于底层是用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,打印后后两行。