GO语言在time包中提供了三种定时器的使用方式:
1.第一种: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
}

通过 time.NewTicker() 创建,这种类型,ticker会不断的按照设定的间隔时间触发,除非主动终止运行。
2.第二种:timer

// The Timer type represents a single event.
// When the Timer expires, the current time will be sent on C,
// unless the Timer was created by AfterFunc.
// A Timer must be created with NewTimer or AfterFunc.
type Timer struct {
C <-chan Time
r runtimeTimer
}

通过 time.NewTimer() 创建,这种类型,timer只会执行一次,当然,可以在执行完以后通过调用 timer.Reset() 让定时器再次工作,并可以更改时间间隔。
3.第三种:After()

// 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
}

从代码可以看到,After()其实是Timer的一个语法糖。

下面通过代码演示一下三种方式的使用:
1.Ticker

ticker := time.NewTicker(time.Second * 1) // 运行时长
ch := make(chan int)
go func() {
var x int
for x < 10 {
select {
case <-ticker.C:
x++
fmt.Printf("%d\n", x)
}
}
ticker.Stop()
ch <- 0
}()
<-ch // 通过通道阻塞,让任务可以执行完指定的次数。

该ticker每1秒触发一次,即ticker.C中每一秒会有一个内容加入,最后通过向ch中写入数字,让程序解除阻塞,继续执行。

2.Timer

timer := time.NewTimer(time.Second * 1) // timer 只能按时触发一次,可通过Reset()重置后继续触发。
go func() {
var x int
for {
select {
case <-timer.C:
x++
fmt.Printf("%d,%s\n", x, time.Now().Format("2006-01-02 15:04:05"))
if x < 10 {
timer.Reset(time.Second * 2)
} else {
ch <- x
}
}
}
}()
<-ch

3.After()

// 阻塞一下,等待主进程结束
tt := time.NewTimer(time.Second * 10)
<-tt.C
fmt.Println("over.")

<-time.After(time.Second * 4)
fmt.Println("再等待4秒退出。tt 没有终止,打印出 over 后会看见在继续执行...")
tt.Stop()
<-time.After(time.Second * 2)
fmt.Println("tt.Stop()后, tt 仍继续执行,只是关闭了 tt.C 通道。")