douchi5822
douchi5822
2018-11-12 18:00

我有一个奇怪的错误

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 duanqiao1949 3年前

    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)
            }
        }
    }
    
    点赞 评论 复制链接分享

为你推荐