golang----定时任务

  1. time.Date 构造出下一次任务执行的时间 next
  2. now.After(next) 判断 next 时间是否已经过去了,如果 true,已经过去了,则往后推一个循环,如果是每天的定时任务,则后推一天
  3. next.Sub(now) 计算下一次任务将在多少秒后执行
  4. 使用 time.NewTicker(duration) 构造一个定时器
  5. for 循环触发定时器,每次触发后再度初始化定时器
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)
       }
    }
}
相关推荐
mldong13 小时前
从 mldong 到 jeeflow:一个工作流引擎的独立进化
后端
陈随易13 小时前
MoonBit抓包模块pcap,查看电脑的每一次联网通信
前端·后端·程序员
Aaron - Wistron14 小时前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
卷无止境14 小时前
写代码这件事,到底该讲究点什么?
后端·python
卷无止境14 小时前
循环复杂度到底在算什么,Python 代码怎么才能写得让人一看就懂
后端·python
IT_陈寒16 小时前
Vite热更新失效?你可能漏了这个配置
前端·人工智能·后端
名字还没想好☜16 小时前
Go 的 time.After 在 select 循环里内存泄漏:定时器堆积原理与 timer.Reset 正确姿势
java·数据库·golang·go·goroutine
SomeB1oody17 小时前
【RustyML入门】1.0. 快速上手
开发语言·后端·机器学习·rust·教程