go - 如何从过去的某个时间开始定期启动cron作业

标签 go cron-task

我想构建一个程序,该程序运行通常在过去的某个时间开始的许多cron作业。这是使用 gocron 的简化示例:

package main

import (
    "time"

    "github.com/jasonlvhit/gocron"
    "github.com/sirupsen/logrus"
)

// This slice would be obtained from persistent storage
var 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秒后立即发生。

但是,由于startTime s是程序启动之前的4和3秒,所以我希望事件分别在程序启动之后6和7秒(以及之后的每10秒)发生。

有没有办法用gocron或其他工具来做到这一点?

最佳答案

这似乎只是简单的数学运算:

    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

关于go - 如何从过去的某个时间开始定期启动cron作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60844625/

相关文章:

go - 如何通过使用aws-sdk-go获取S3返回的xml格式错误响应?

go - 如何测试光纤参数

linux - 安装 ssmtp 用于发送电子邮件后的虚拟 cron 作业

ubuntu - 用于 shell 的 crontab 不工作

linux - 为什么这一行删除所有内容而不是一行。 Crontab-Bash-Sed

go - 等到满足条件或超时

date - Go 编程语言如何处理日期和时间?

go - AWS Cognito 刷新 token 在 secret 哈希上失败

cron - 通过 Cron 将当前日期附加到文件名?

python - 如何每隔 2 分钟运行 100 个 python 文件?