我在使用 time.Tick
时遇到困难。我希望这段代码打印“hi”10 次,然后在 1 秒后退出,但它却挂起:
ticker := time.NewTicker(100 * time.Millisecond)
time.AfterFunc(time.Second, func () {
ticker.Stop()
})
for _ = range ticker.C {
go fmt.Println("hi")
}
https://play.golang.org/p/1p6-ViSvma
查看source ,我发现调用 Stop()
时 channel 并未关闭。在这种情况下,迭代股票 channel 的惯用方法是什么?
最佳答案
你是对的,股票行情 channel 并没有在停止时关闭,正如 documentation 中所述。 :
Stop turns off a ticker. After Stop, no more ticks will be sent. Stop does not close the channel, to prevent a read from the channel succeeding incorrectly.
我相信 Ticker 更多的是关于即发即忘,即使您想停止它,您甚至可以让例程永远挂起(当然取决于您的应用程序)。
如果你确实需要一个有限的股票代码,你可以采取一些技巧并提供一个单独的 channel (根据 ThunderCat 的答案),但我要做的是提供我自己的股票代码实现。这应该相对容易,并且会给您提供其行为的灵活性,例如在 channel 上传递什么或决定如何处理丢失的刻度(即当读者落后时)。
我的例子:
func finiteTicker(n int, d time.Duration) <-chan time.Time {
ch := make(chan time.Time, 1)
go func() {
for i := 0; i < n; i++ {
time.Sleep(d)
ch <- time.Now()
}
close(ch)
}()
return ch
}
func main() {
for range finiteTicker(10, 100*time.Millisecond) {
fmt.Println("hi")
}
}
关于go - 如何迭代 go time.Tick channel ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31083572/