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 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!