go的标准库中的time包为我们提供了多个定时器的接口,总共分为以下几个:
- time.After,到了给定的duration的时间时,返回可读chan,也不会阻止程序运行,相当于一个消息通知
- time.Sleep,在给定的duration中,阻塞当前goroutine,过了休眠时间,goroutine继续运行
- time.Tick,每隔给定的duration,返回一个chan作为消息通知,除非外在stop,否则一直运行
- time.Ticker,与Tick的不同就是,提供了Stop接口,在给定时间到达后,Ticker会停止
根据不同的应用场景进行选择。
下面给出简单的应用代码,仅供参考:
package main
import (
"fmt"
"time"
)
func main() {
// 1. time.After, only read tchan will block
fmt.Println("time.After test...")
tchan := time.After(1 * time.Second)
fmt.Println(time.Now().String())
fmt.Println(time.Now().String(), "tchan=", <-tchan)
fmt.Println(time.Now().String())
// 2. time.Sleep
fmt.Println("\ntime.Sleep test...")
fmt.Println(time.Now().String())
time.Sleep(5 * time.Second)
fmt.Println(time.Now().String())
// 3. time.Tick, every d will recv time.Time, cannot stop by self
fmt.Println("\ntime.Tick test...")
/*
c := time.Tick(2 * time.Second)
for next := range c {
fmt.Println(next)
}
*/
// 4. time.Ticker, like time.Tick, but can stop
fmt.Println("\ntime.Ticker test...")
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
done := make(chan bool)
// after 5 seconds, stop
go func() {
time.Sleep(5 * time.Second)
done <- true
}()
// loop for ticker
for {
select {
case <- done:
fmt.Println("done!")
return
case t := <- ticker.C:
fmt.Println("Current time:", t)
}
}
}
标签:定时器,fmt,After,tchan,给定,time,go
From: https://www.cnblogs.com/davis12/p/17024268.html