【问题标题】:How to add wait time in for loop如何在for循环中添加等待时间
【发布时间】:2021-03-02 15:08:46
【问题描述】:

我有一个文件列表,我必须每隔 5 秒处理一次。

这里是主要方法:

func main() {
    pusher := pusher.NewPusher(10)
    // goroutine to consume channel
    go pusher.Start()

    shutdownGatherer := make(chan struct{})
    go func() {
        ticker := time.NewTicker(time.Second * 5)
        defer ticker.Stop()
        for {
            select {
            case <-shutdownGatherer:
                log.Infof("Gatherer received shutdown signal, stopping.")
                return
            case t := <-ticker.C:
                log.Infof("\n **** Gatherer Tick at: %s ****\n", t)
                go gather(pusher)
            }
        }
    }()
    log.Infof("Done.")
    time.Sleep(time.Second * 1000)
}

gather 方法必须在每个文件添加到通道之前添加一些等待时间(随机 O 到 5 秒):

func gather(p *pusher.Pusher) {
    regularFilePaths, _ := filepath.Glob("../files/*")
    for _, filePath := range regularFilePaths {
        p.Enqueue(filePath)
    }
}

你可以在这里找到推送文件:pusher.go

假设我们有文件:

  • test1.txt

  • test2.txt

  • ...

  • test100.txt

          First interval: 
          2sec sleep --> Add test1.txt to channel for processing
          3sec sleep --> Add test2.txt to channel for processing
          5sec passed
    
      -----------
    
          Second interval: 
          1sec sleep --> Add test3.txt to channel for processing
          2sec sleep --> Add test4.txt to channel for processing
          3sec sleep --> Add test5.txt to channel for processing
          5sec passed
    
      -----------
    
          3rd interval: 
          5sec sleep --> Add test6.txt to channel for processing
          5sec passed
    

我的问题是睡眠,需要超过 5 秒的时间间隔。 而且睡眠似乎没有按预期工作。

您能否在这里给我一个更好的方法:

【问题讨论】:

标签: go


【解决方案1】:

在大多数生产环境中,我们希望使用速率限制器,而不是使用持续等待。 Token Bucket 是一个很棒的实现,这里是 Uber 的 Go 实现。

https://github.com/uber-go/ratelimit

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-18
    • 2023-01-20
    • 2018-06-09
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多