更多内容请关注微信公众号:Go程序员开发
定时器可以实现在指定时间点执行特定的事件。Go语言定时器和其他语言的开发思路不一样。其他语言大多是注册回调函数定时,时间到了调用回调。
一次性定时器
一、使用 time.NewTimer 实现一次性定时器:
package main
import (
"fmt"
"time"
)
func main() {
t := time.NewTimer(2 * time.Second)
now := time.Now()
fmt.Printf("Now time: %v\n", now)
expire := <-t.c
fmt.Printf("Expire time: %v\n", expire)
}
二、使用 time.After 实现一次性定时器:
package main
import (
"fmt"
"time"
)
func main() {
start := time.Now()
select {
case <-time.After(time.Second * 5): // 5秒后执行
// <- time.After(周期):
fmt.Println("after")
}
duration := time.Since(start)
fmt.Println("运行时间:", duration)
}