我一直在寻找有关如何实现功能的示例,该功能允许您在Go中的特定时间执行任务,但是我什么也找不到。
我自己实现了自己,并在答案中分享了它,以便其他人可以为自己的实现提供引用。
最佳答案
这是一个常规实现,可让您设置:
更新:(已修复内存泄漏)
import (
"fmt"
"time"
)
const INTERVAL_PERIOD time.Duration = 24 * time.Hour
const HOUR_TO_TICK int = 23
const MINUTE_TO_TICK int = 00
const SECOND_TO_TICK int = 03
type jobTicker struct {
timer *time.Timer
}
func runningRoutine() {
jobTicker := &jobTicker{}
jobTicker.updateTimer()
for {
<-jobTicker.timer.C
fmt.Println(time.Now(), "- just ticked")
jobTicker.updateTimer()
}
}
func (t *jobTicker) updateTimer() {
nextTick := time.Date(time.Now().Year(), time.Now().Month(),
time.Now().Day(), HOUR_TO_TICK, MINUTE_TO_TICK, SECOND_TO_TICK, 0, time.Local)
if !nextTick.After(time.Now()) {
nextTick = nextTick.Add(INTERVAL_PERIOD)
}
fmt.Println(nextTick, "- next tick")
diff := nextTick.Sub(time.Now())
if t.timer == nil {
t.timer = time.NewTimer(diff)
} else {
t.timer.Reset(diff)
}
}
关于cron - Golang : Implementing a cron/executing tasks at a specific time,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19549199/