給出了以下兩個功能。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 分鐘的間隔。有人知道為什么會這樣嗎?
1 回答

SMILET
TA貢獻1796條經驗 獲得超4個贊
我建議使用 atime.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)
? ? ? ? }
? ? }
}
- 1 回答
- 0 關注
- 134 瀏覽
添加回答
舉報
0/150
提交
取消