Golang Timer用法
in Go with 0 comment

Golang Timer用法

in Go with 0 comment

基于Go1.13

创建、停止、重置

一次性Timer

func NewTimer(d Duration) *Timer
// 支持Stop、Reset

周期性Timer

func NewTicker(d Duration) *Ticker
// 支持Stop

NewTicker的包装

func Tick(d Duration) <-chan Time

当达到指定时间时,chan的返回值为time.Now()

用法

func main() {
	d := time.Second
	t := time.NewTicker(d)
	defer t.Stop()
	for {
		<-t.C
		log.Println("timeout...")
	}
}
// 2020/07/20 00:06:10 timeout...
// 2020/07/20 00:06:11 timeout...
// 2020/07/20 00:06:12 timeout...
// 2020/07/20 00:06:13 timeout...
func main() {
	d := time.Second
	t := time.NewTimer(d)
	defer t.Stop()
	<-t.C
	log.Println("timeout...")
}
// 2020/07/20 00:07:06 timeout...
func main() {
	d := time.Second
	t := time.NewTimer(d)
	defer t.Stop()
	for {
		<-t.C
		log.Println("timeout...")
		t.Reset(time.Second)
	}
}
// 2020/07/20 00:07:50 timeout...
// 2020/07/20 00:07:51 timeout...
// 2020/07/20 00:07:52 timeout...
// 2020/07/20 00:07:53 timeout...
func main() {
	d := time.Second
	// t := time.NewTicker(d)
	t := time.Tick(d)
	for range t {
		log.Println("timeout...")
	}
}

// 2020/07/20 00:10:37 timeout...
// 2020/07/20 00:10:38 timeout...
// 2020/07/20 00:10:39 timeout...
// 2020/07/20 00:10:40 timeout...
func main() {
   log.Println(time.Now())
   <- time.After(1 * time.Second)
   log.Println(time.Now())
}

// 2020/07/20 23:50:44 2020-07-20 23:50:44.924367 +0800 CST m=+0.000094541
// 2020/07/20 23:50:45 2020-07-20 23:50:45.925691 +0800 CST m=+1.001411484
func main() {
   log.Println("AfterFuncDemo start: ", time.Now())
   // 会启动一个新的goroutine运行该func
   time.AfterFunc(1 * time.Second, func() {
      log.Println("AfterFuncDemo end: ", time.Now())
   })

   time.Sleep(2 * time.Second) // 等待协程退出
}

// 2020/07/20 23:51:17 AfterFuncDemo start:  2020-07-20 23:51:17.201096 +0800 CST m=+0.000109548
// 2020/07/20 23:51:18 AfterFuncDemo end:  2020-07-20 23:51:18.204792 +0800 CST m=+1.003800076

参考资料

https://my.oschina.net/renhc/blog/3026957