go - 如何迭代 go time.Tick channel ?

标签 go

我在使用 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")
    }
}

http://play.golang.org/p/ZOwJlM8rDm

关于go - 如何迭代 go time.Tick channel ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31083572/

相关文章:

json - 将具有 JSON 数组的 JSON 对象解码为结构

networking - 使用 ResponseWriter.Write 在 Go 中连接 250 次后出现 "localhost: no such host"

Golang filepath.Walk 大目录上的 panic 错误

xml - 在 Go 中将 Marshall 映射到 XML

将 interface{} 转换为 map

Golang猴子补丁

Go type 在它看起来不应该的时候自动转换

shell - 在同一个 shell golang 中运行多个 Exec 命令

pointers - 如何检测golang中的结构指针是否为nil?

go - 映射键的惯用 else if 链