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

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

如何從過去的某個時間開始定期啟動 cron 作業

如何從過去的某個時間開始定期啟動 cron 作業

Go
汪汪一只貓 2022-05-23 16:30:13
我想構建一個程序,它運行多個 cron 作業,這些作業通常在過去的某個時間開始。這是一個使用的簡化示例gocron:package mainimport (    "time"    "github.com/jasonlvhit/gocron"    "github.com/sirupsen/logrus")// This slice would be obtained from persistent storagevar startTimes = []time.Time{    time.Now().Add(-4 * time.Second),    time.Now().Add(-3 * time.Second),}func format(t time.Time) string {    return t.Format("15:04:05")}func notify(startTime time.Time) {    logrus.WithField("time", format(time.Now())).Infof("I started at %s\n", format(startTime))}func main() {    for _, startTime := range startTimes {        gocron.Every(10).Seconds().From(&startTime).Do(notify, startTime)    }    logrus.Infof("Starting at %s...\n", format(time.Now()))    <-gocron.Start()}如果我運行它,我會得到以下輸出:INFO[0000] Starting at 00:30:54...                      INFO[0010] I started at 00:30:50                         fields.time="00:31:04"INFO[0010] I started at 00:30:51                         fields.time="00:31:04"我觀察到所有事件都在我啟動程序后 10 秒同時發生。但是,由于startTimes 是程序啟動前 4 秒和 3 秒,我希望事件分別在程序啟動后 6 秒和 7 秒(以及之后每 10 秒)發生一次。有沒有辦法用gocron或其他工具做到這一點?
查看完整描述

2 回答

?
慕村9548890

TA貢獻1884條經驗 獲得超4個贊

這似乎只是簡單的數學運算:


    interval := 10 * time.Second

    nextTime := time.Now().Add((time.Since(startTime) + interval) % interval)

    gocron.Every(10).Seconds().From(&nextTime).Do(notify, nextTime)

https://play.golang.org/p/pwEZqy_LUuk


查看完整回答
反對 回復 2022-05-23
?
手掌心

TA貢獻1942條經驗 獲得超3個贊

我們可以嘗試利用一個簡單的代碼,它不是一個完整的解決方案,但應該很容易適應。


package main


import (

    "fmt"

    "time"

)


func ticker(period time.Duration, length ...time.Duration) <-chan time.Time {

    ticker := time.NewTicker(period)


    if len(length) > 0 {

        done := make(chan bool)

        go func() {

            time.Sleep(period + length[0])

            done <- true

        }()


        go func() {

            <-done

            ticker.Stop()

        }()

    }


    return ticker.C


}


func main() {

    t1 := ticker(6*time.Second, 4*time.Second)

    t2 := ticker(7*time.Second, 3*time.Second)

    t3 := ticker(10 * time.Second)

    for {

        select {

        case t1 := <-t1:

            fmt.Println("t1: ", t1)

        case t2 := <-t2:

            fmt.Println("t2: ", t2)

        case t3 := <-t3:

            fmt.Println("t3: ", t3)

        }

    }

}


查看完整回答
反對 回復 2022-05-23
  • 2 回答
  • 0 關注
  • 177 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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