golang的timer的一些坑
需求
最近项目有一些定时任务的需求,如每天的早上10:00:00定时的去执行一些任务。
问题
但是我遇到了一些问题,就是我定时10:00:00去执行,但是这个定时器疯狂的翻滚停不下来了,代码如下
package main
import (
"fmt"
"time"
)
func main() {
//每天10:05 通报昨日报警数量统计
go func() {
for {
// 定时器会一直执行
now := time.Now()
// 计算明天的时间
next := now.Add(time.Hour * 24 * time.Duration(0))
// 10:00 进行提醒
next = time.Date(next.Year(), next.Month(), next.Day(), 10, 0, 0, 0, next.Location())
fmt.Println("now:", next)
fmt.Println("next:", next)
fmt.Println("next.Sub(now:", next.Sub(now))
timer := time.NewTimer(next.Sub(now))
select {
case ts := <-timer.C:
fmt.Println("Start YesterdayAlarmStatistics ts=%s", ts.String())
}
}
}()
for {
}
}
控制台打印
Start YesterdayAlarmStatistics ts=%s 2022-04-02 14:49:34.505853<
Golang 定时任务实现与常见问题解析

本文介绍了在Golang中实现定时任务时遇到的问题,如定时器无限循环。分析了问题原因在于`time.Timer`的`Stop`方法仅移除定时器,不关闭通道。提出了两种解决方案:一是通过检查`Stop`返回值并关闭通道来确保单次执行;二是根据当前时间动态调整下次执行时间。此外,还给出了每周一10点执行任务的实现方法。
最低0.47元/天 解锁文章
2517





