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)
       }
    }
}
相关推荐
canonical_entropy19 分钟前
不同的工作需要不同人格的AI大模型?
人工智能·后端·ai编程
IT_陈寒29 分钟前
Vite 5.0 终极优化指南:7个配置技巧让你的构建速度提升200%
前端·人工智能·后端
小熊学Java33 分钟前
基于 Spring Boot+Vue 的高校竞赛管理平台
vue.js·spring boot·后端
钢门狂鸭6 小时前
关于rust的crates.io
开发语言·后端·rust
脑子慢且灵7 小时前
[JavaWeb]模拟一个简易的Tomcat服务(Servlet注解)
java·后端·servlet·tomcat·intellij-idea·web
华仔啊8 小时前
SpringBoot 中 6 种数据脱敏方案,第 5 种太强了,支持深度递归!
java·后端
刘媚-海外10 小时前
Go语言开发AI应用
开发语言·人工智能·golang·go
勇敢牛牛_10 小时前
使用Rust实现服务配置/注册中心
开发语言·后端·rust·注册中心·配置中心
deepwater_zone11 小时前
Go语言核心技术
后端·golang
爱干饭的boy13 小时前
手写Spring底层机制的实现【初始化IOC容器+依赖注入+BeanPostProcesson机制+AOP】
java·数据结构·后端·算法·spring