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)
       }
    }
}
相关推荐
bagadesu33 分钟前
MySQL----case的用法
java·后端
百***58141 小时前
Spring Boot 2.7.x 至 2.7.18 及更旧的版本,漏洞说明
java·spring boot·后端
q***38512 小时前
Spring boot启动原理及相关组件
数据库·spring boot·后端
q***04052 小时前
Spring Boot项目中解决跨域问题(四种方式)
spring boot·后端·dubbo
q***64972 小时前
Spring BOOT 启动参数
java·spring boot·后端
百***62852 小时前
Spring Boot 3.X:Unable to connect to Redis错误记录
spring boot·redis·后端
我命由我123453 小时前
Java 开发 - 粘包处理器 - 基于消息头 + 消息体(魔数验证、长度验证)
java·网络·后端·网络协议·java-ee·intellij-idea·intellij idea
csdn_wuwt3 小时前
有C#可用的开源的地图吗?
后端·c#·gis·map·开发·设计·地图
bagadesu3 小时前
15.<Spring Boot 日志>
java·后端
9ilk4 小时前
【基于one-loop-per-thread的高并发服务器】--- 项目测试
运维·服务器·c++·后端·中间件