go - 我有一个奇怪的错误

标签 go

给出了以下两个函数。

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...
    }
}

我想每 10/60/3600 秒执行一次。所以我认为带模数的递增索引应该做到这一点。

但我注意到(尤其是在高流量服务器上)它似乎跳过了一些循环。

我查看了我的日志,有时每 10 秒就会有一些东西,但有时会有长达 1 分钟的间隔。

有人知道为什么会这样吗?

最佳答案

我建议使用 time.Ticker每 N 秒执行一次操作。这样,您就可以使用内置计时器,并且仅在需要做某事时才唤醒 CPU。即使 CPU 使用率不高,time.Sleep 和 for 循环也不是最可靠的任务调度方式。例如(来自上面的链接):

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)
        }
    }
}

关于go - 我有一个奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53267664/

相关文章:

go - 如何使用golang和数组数据创建json数据

go - 不能用作 go 中的分配类型

templates - Golang 从文件中嵌入 html

go - Docker 在完成 Golang 项目构建之前退出

arrays - 在字节数组上使用json.Unmarshal()时出现问题

Go Refllect 声明类型结构

json - 在 Golang 中将表单值分配给结构

macos - Go - 使用 xgo 库与 CGO 交叉编译

Golang return map[string]interface{} 返回变量结构

Go Modules : finding out right pseudo-version (vX. Y.Z-<timestamp>-<commit>) 所需包