GO-time.after 用法

初学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,打印后后两行。