ticker结构,一个有计时的通道的定时器,到一个时间点就触发。
// A Ticker holds a channel that delivers `ticks' of a clock
// at intervals.
type Ticker struct {
C <-chan Time // The channel on which the ticks are delivered.
r runtimeTimer
}
先来一个例子:这里实现了俩个计时,一个是每2秒打印一个tick,还有一个是到20秒之后结束。
package main
import (
"fmt"
"time"
)
func main(){
tim:=time.Tick(time.Second*20)
tc:=time.NewTicker(time.Second*2)
defer tc.Stop()
done:=make(chan bool)
var i=0
go func() {
for{
select {
case <- tim:
fmt.Printf("shijian" )
tc.Stop()
done<-true
case <-tc.C:
i++
fmt.Printf("tick ,%v\n",i )
}
}
}()
<-done
fmt.Printf("end",i )
}
简单说一下俩个计时的不同实现
tc:=time.NewTicker(time.Second*2)
defer tc.Stop()
记得把ticker关闭,这边是生成一个Ticker,Ticker本身就带有一个channel,用来阻塞的,当时间到了,select的触发第二个case(也不算是触发,select在for下循环的,如果某个case的channel不阻塞的话执行后面的操作)
tim:=time.Tick(time.Second*20)
// Tick is a convenience wrapper for NewTicker providing access to the ticking
// channel only. While Tick is useful for clients that have no need to shut down
// the Ticker, be aware that without a way to shut it down the underlying
// Ticker cannot be recovered by the garbage collector; it "leaks".
// Unlike NewTicker, Tick will return nil if d <= 0.
func Tick(d Duration) <-chan Time {
if d <= 0 {
return nil
}
return NewTicker(d).C
}
还有一个20秒的定时器,使用time包的Tick实现的,它的方法如上。可以看一下它的说明,简单来说就是生成一个Ticker的channel,不通过Ticker结构来。
所以代码中tim 和 tc.C都是一个channel。
再通过
go func() {
for{
select {
case <- tim:
fmt.Printf("shijian" )
tc.Stop()
done<-true
case <-tc.C:
i++
fmt.Printf("tick ,%v\n",i )
}
}
}()
起一个携程,让它一直跑。当到了20秒,通过done向主协程传送信息,结束。
主要是用了select机制。
贴个结果
补充一个常用的定时方法
fmt.Printf("end\n",time.Now() )
time.AfterFunc(time.Second*2, func() {
fmt.Print("after\n" ,time.Now())
})
time.Sleep(time.Second*3)//为了不让主线程退出,睡一会
在之前的main中跑一下。