donglan6777 2015-06-26 23:26
浏览 45
已采纳

如何遍历go.Tick频道?

I'm having difficulty using time.Tick. I expect this code to print "hi" 10 times then quit after 1 second, but instead it hangs:

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

Looking at the source, I see that the channel isn't closed when Stop() is called. In that case, what is the idiomatic way to iterate over the ticker channel?

  • 写回答

2条回答 默认 最新

  • dongyun9120 2015-06-27 10:53
    关注

    You're right, ticker's channel is not being closed on stop, that's stated in a 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.

    I believe ticker is more about fire and forget and even if you want to stop it, you could even leave the routine hanging forever (depends on your application of course).

    If you really need a finite ticker, you can do tricks and provide a separate channel (per ThunderCat's answer), but what I would do is providing my own implementation of ticker. This should be relatively easy and will give you flexibility with its behaviour, things like what to pass on the channel or deciding what to do with missing ticks (i.e. when reader is falling behind).

    My example:

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3