亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 golang 的特定紀元時間啟動 cronjob

在 golang 的特定紀元時間啟動 cronjob

Go
阿晨1998 2023-01-03 14:14:11
我正在使用github.com/robfig/cron庫。我想以毫秒為單位在 epoc 時間運行 cronjob 并每秒工作。cron 從000毫秒開始。我需要它在特定時間開始。例如,如果我采取以下內容:c := cron.New() c.AddFunc("@every 1s", func() {        // Do Something     }) c.Start()并在 epoc 時間戳運行它,1657713890300然后我希望函數在以下時間運行:165771389130016577138923001657713893300.目前,cron 運行于165771389100016577138920001657713893000.這可能嗎?
查看完整描述

1 回答

?
寶慕林4294392

TA貢獻2021條經驗 獲得超8個贊

當您使用@every 1s庫時,會創建一個ConstantDelaySchedule“循環,以便下一次激活時間將在第二個”。

如果這不是您想要的,那么您可以創建自己的調度程序(游樂場):

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.Timepassed to Nextwhich is time.Now()so will the time會隨著時間慢慢推進。

解決這個問題是可能的(見下文 -游樂場),但這樣做會引入一些潛在的發行者(CustomConstantDelaySchedule不能重復使用,如果作業運行時間太長,那么你仍然會以差異告終)。我建議您考慮放棄 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

}


查看完整回答
反對 回復 2023-01-03
  • 1 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號