两种类型的定时器:ticker和timer。两者有什么区别呢?请看如下代码:
ticker
package main
import (
"fmt"
"time"
)
func main() {
d := time.Duration(time.Second*2)
t := time.NewTicker(d)
defer t.Stop()
for {
<- t.C
fmt.Println("timeout...")
}
}
output:
timeout...
timeout...
timeout...
解析
ticker只要定义完成,从此刻开始计时,不需要任何其他的操作,每隔固定时间都会触发。
timer
package main
import (
"fmt"
"time"
)
func main() {
d := time.Duration(time.Second*2)
t := time.NewTimer(d)
defer t.Stop()
for {
<- t.C
fmt.Println("timeout...")
// need reset
t.Reset(time.Second*2)
}
}
output:
timeout...
timeout...
timeout...
解析
使用timer定时器,超时后需要重置,才能继续触发。
ticker 例子展示
package main
import (
"fmt"
"time"
)
func main() {
t := time.NewTicker(3*time.Second)
defer t.Stop()
fmt.Println(time.Now())
time.Sleep(4*time.Second)
for {
select {
case <-t.C:
fmt.Println(time.Now())
}
}
}
output:
2018-04-02 19:08:22.2797 +0800 CST
2018-04-02 19:08:26.3087 +0800 CST
2018-04-02 19:08:28.2797 +0800 CST
2018-04-02 19:08:31.2797 +0800 CST
2018-04-02 19:08:34.2797 +0800 CST