登录
首页 >  Golang >  Go问答

在for循环中如何加入延迟时间

来源:stackoverflow

时间:2024-03-14 20:00:28 115浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《在for循环中如何加入延迟时间》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我有一个文件列表,必须每隔 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)
}

在将每个文件添加到通道之前,收集方法必须为其添加一些等待时间(随机 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 秒的时间间隔。 而且睡眠似乎没有按预期进行。

您能否在这里为我提供更好的方法:


解决方案


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

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

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>