douchi5822 2018-11-12 18:00
浏览 27
已采纳

我有一个奇怪的错误

given are the following 2 functions.

func main() {
    index := int(0)

    for {
        Loop(index)
        index = (index + 1) % 86400 // Max interval: 1 day
        time.Sleep(1 * time.Second)
    }
}

func Loop(index int) {
    if index%10 == 0 {
        go doSomething...
    }
}

I want to execute something every 10/60/3600 seconds. So I thought an incrementing index with modulo should do this.

But what I noticed (especially on high traffic servers) that it appears to skip some of that loops.

I looked in my logs and sometimes there is something every 10 seconds but sometimes there is a gap up to 1 minute.

Does anybody know why this is happening?

  • 写回答

1条回答 默认 最新

  • duanqiao1949 2018-11-12 18:11
    关注

    I'd recommend using a time.Ticker to perform some action every N seconds. That way, you use built-in timers and only wake the CPU when something needs to be done. Even if the CPU is not heavily used, time.Sleep and a for loop is not the most reliable way to schedule tasks. For example (from the link above):

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        ticker := time.NewTicker(time.Second)
        defer ticker.Stop()
        done := make(chan bool)
        go func() {
            time.Sleep(10 * time.Second)
            done <- true
        }()
        for {
            select {
            case <-done:
                fmt.Println("Done!")
                return
            case t := <-ticker.C:
                fmt.Println("Current time: ", t)
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题