go
复制代码
package main
import (
"fmt"
"time"
)
func main() {
// 每天的3点执行
hour := 3
minute := 0
second := 0
now := time.Now()
// 计算下一个3点时刻
next := time.Date(now.Year(), now.Month(), now.Day(), hour, minute, second, 0, now.Location())
if now.After(next) {
next = next.Add(24 * time.Hour)
}
duration := next.Sub(now)
fmt.Printf("下一次任务将在 %s 秒后执行", duration)
timer := time.NewTicker(duration)
defer timer.Stop()
// 定时调用
for {
select {
case <-timer.C:
fmt.Println("执行定时任务")
// 重新计算下一个3点时刻
now := time.Now()
next := time.Date(now.Year(), now.Month(), now.Day(), hour, minute, second, 0, now.Location())
next = next.Add(24 * time.Hour)
duration = next.Sub(now)
timer.Stop()
timer = time.NewTicker(duration)
fmt.Printf("下一次任务将在 %s 秒后执行", duration)
}
}
}