package main
import (
"log"
"time"
)
func main() {
per := 10
period := time.Duration(per) * time.Second
log.Printf("period : %d sec\n\n", per)
ticker := time.NewTicker(time.Until(time.Now().Truncate(period).Add(period)))
for {
curTime := <-ticker.C
log.Printf("started %s", curTime.Format("2 15:04:05"))
time.Sleep(5 * time.Second)
log.Printf("ended %s\n\n", curTime.Format("2 15:04:05"))
}
}当我使用time.Sleep inside ticker时,ticker停止正常工作,我希望该ticker每10秒启动一次,但我在屏幕截图上看到了结果。我怎样才能正确地做这件事呢?enter image description here
发布于 2021-03-26 07:02:36
您的代码正常工作,但您打印的时间不对。
for {
curTime := <-ticker.C
log.Printf("started %s", curTime.Format("2 15:04:05"))
time.Sleep(5 * time.Second)
log.Printf("ended %s\n\n", curTime.Format("2 15:04:05"))
}curTime是刻度的时间,所以这两次打印相同的时间。相反,您应该使用time.Now()来获取当前时间。
for {
tickTime := <-ticker.C
log.Printf("tick %s", tickTime.Format("2 15:04:05"))
time.Sleep(5 * time.Second)
log.Printf("after sleep %s\n\n", time.Now().Format("2 15:04:05"))
}而且,由于NewTicker需要一个持续时间,因此可以简化。
per := 10
period := time.Duration(per) * time.Second
// Rather than printing the number in `per` and assuming it's
// seconds, print the duration which can format itself.
log.Printf("period : %s\n\n", period)
// NewTicker takes a Duration which we already have.
ticker := time.NewTicker(period)然后你会在10秒内得到正确的5秒睡眠。
2021/03/25 16:02:49 period : 10 sec
2021/03/25 16:02:59 tick 25 16:02:59
2021/03/25 16:03:04 after sleep 25 16:03:04
2021/03/25 16:03:09 tick 25 16:03:09
2021/03/25 16:03:14 after sleep 25 16:03:14发布于 2021-03-26 06:55:17
替换
ticker := time.NewTicker(time.Until(time.Now().Truncate(period).Add(period)))使用
ticker := time.NewTicker(period)看看这能不能用。
https://stackoverflow.com/questions/66808604
复制相似问题