1 回答

TA貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個(gè)贊
當(dāng)您使用@every 1s
該庫時(shí),會創(chuàng)建一個(gè)ConstantDelaySchedule
“循環(huán),以便下一次激活時(shí)間將在第二個(gè)”。
如果這不是您想要的,那么您可以創(chuàng)建自己的調(diào)度程序(游樂場):
package main
import (
"fmt"
"time"
"github.com/robfig/cron/v3"
)
func main() {
time.Sleep(300 * time.Millisecond) // So we don't start cron too near the second boundary
c := cron.New()
c.Schedule(CustomConstantDelaySchedule{time.Second}, cron.FuncJob(func() {
fmt.Println(time.Now().UnixNano())
}))
c.Start()
time.Sleep(time.Second * 5)
}
// CustomConstantDelaySchedule is a copy of the libraries ConstantDelaySchedule with the rounding removed
type CustomConstantDelaySchedule struct {
Delay time.Duration
}
// Next returns the next time this should be run.
func (schedule CustomConstantDelaySchedule) Next(t time.Time) time.Time {
return t.Add(schedule.Delay)
}
Follow up: 上面使用的是time.Time
passed to Next
which is time.Now()
so will the time會隨著時(shí)間慢慢推進(jìn)。
解決這個(gè)問題是可能的(見下文 -游樂場),但這樣做會引入一些潛在的發(fā)行者(CustomConstantDelaySchedule
不能重復(fù)使用,如果作業(yè)運(yùn)行時(shí)間太長,那么你仍然會以差異告終)。我建議您考慮放棄 cron 包,而只使用time.Ticker
.
package main
import (
"fmt"
"time"
"github.com/robfig/cron/v3"
)
func main() {
time.Sleep(300 * time.Millisecond) // So we don't start cron too nead the second boundary
c := cron.New()
c.Schedule(CustomConstantDelaySchedule{Delay: time.Second}, cron.FuncJob(func() {
fmt.Println(time.Now().UnixNano())
}))
c.Start()
time.Sleep(time.Second * 5)
}
// CustomConstantDelaySchedule is a copy of the libraries ConstantDelaySchedule with the rounding removed
// Note that because this stored the last time it cannot be reused!
type CustomConstantDelaySchedule struct {
Delay time.Duration
lastTarget time.Time
}
// Next returns the next time this should be run.
func (schedule CustomConstantDelaySchedule) Next(t time.Time) time.Time {
if schedule.lastTarget.IsZero() {
schedule.lastTarget = t.Add(schedule.Delay)
} else {
schedule.lastTarget = schedule.lastTarget.Add(schedule.Delay)
}
return schedule.lastTarget
}
- 1 回答
- 0 關(guān)注
- 146 瀏覽
添加回答
舉報(bào)