主要就是定时器,标准库中的Timer让用户可以定义自己的超时逻辑,尤其是在应对select处理多个channel的超时、单channel读写的超时等情形时尤为方便。
Timer是一次性的时间触发事件,这点与Ticker不同,Ticker是按一定时间间隔持续触发时间事件。
Timer常见的创建方式:
t:= time.NewTimer(d)t:= time.AfterFunc(d, f)c:= time.After(d)
虽然说创建方式不同,但是原理是相同的。
Timer有3个要素:
定时时间:就是那个d触发动作:就是那个f时间channel: 也就是t.C
一、time.NewTimer()
NewTimer()创建一个新的计时器,该计时器将在其通道上至少持续d之后发送当前时间。

它的返回值是一个Timer。
源代码:
// NewTimer creates a new Timer that will send// the current time on its channel after at least duration d.func NewTimer(d Duration) *Timer { c := make(chan Time, 1) t := &Timer{ C: c, r: runtimeTimer{ when: when(d), f: sendTime, arg: c, }, } startTimer(&t.r) return t}通过源代码我们可以看出,首先创建一个channel,关联的类型为Time,然后创建了一个Timer并返回。
用于在指定的Duration类型时间后调用函数或计算表达式。如果只是想指定时间之后执行,使用time.Sleep()使用NewTimer(),可以返回的Timer类型在计时器到期之前,取消该计时器直到使用<-timer.C发送一个值,该计时器才会过期
示例代码:
package mainimport ( "time" "fmt")func main() { //新建一个计时器:timer timer := time.NewTimer(3 * time.Second) fmt.Printf("%Tn", timer) / //新建一个计时器:timer //timer := time.NewTimer(3 * time.Second) //fmt.Printf("%Tn", timer) / ch1 := time.After(3 * time.Second) //3s后 fmt.Printf("%Tn", ch1) // <-chan time.Time fmt.Println(time.Now()) //2019-08-15 09:56:41.529883 +0800 CST m=+0.000465158 time2 := <-ch1 fmt.Println(time2) //2019-08-15 09:56:44.532047 +0800 CST m=+3.002662179}运行结果:



