【发布时间】:2021-03-02 04:56:11
【问题描述】:
我想在每天晚上 9 点打印出do my job。如何在 Go 中执行此操作?
这是我目前所得到的:
timer := time.NewTimer(3 * time.Second)
for {
now := time.Now()
next := now.Add(time.Hour * 24)
todayNine := time.Date(next.Year(), next.Month(), next.Day(), 9, 0, 0, 0, next.Location()).AddDate(0, 0, -1)
todayFifteen := time.Date(next.Year(), next.Month(), next.Day(), 15, 0, 0, 0, next.Location()).AddDate(0, 0, -1)
todayEnd := time.Date(next.Year(), next.Month(), next.Day(), 0, 0, 0, 0, next.Location()).AddDate(0, 0, -1)
if now.Before(todayNine) {
timer.Reset(todayNine.Sub(now))
} else if now.Before(todayFifteen) {
timer.Reset(todayFifteen.Sub(now))
} else if now.Before(todayEnd) {
timer.Reset(todayEnd.Sub(now))
}
<- timer.C
fmt.Println("do my job")
}
【问题讨论】:
-
您可以使用 ticker 并检查小时部分 time.Now() 。但是如果您的服务有多个实例正在运行,那就会很棘手..您最终将每个实例都执行一次。
-
我建议在 go 二进制文件之外使用不同的系统来启动作业。它可以是 cron 作业或 k8 cron。如果你想纯粹使用 go "ticker" 来做,应该使用
-
您的操作系统可能有一种方法可以安排程序在您想要的特定时间定期运行。您使用的是什么操作系统?
-
抱歉没有尽快回复,这是我的解决方案,请告诉我您的想法,谢谢!