实现了一个定时器,但是只能在当天凌晨运行一次,第二天凌晨运行失效,怎么回事呢?

需求是实现一个定时任务,在每天凌晨执行某个任务。现在的实现如下,在运行过程中,发现当天的凌晨确实执行了任务,但是第二天就失效。


type notifyTicker struct {
T *time.Timer
}

func iniMonitor() {
jt := NewMonitorTicker()
for {
<-jt.T.C
beego.Warn("Is timer active?", jt.UpdateJobTicker())
}
}

func getNextTickDuration() time.Duration {
now := time.Now()
nextTick := time.Date(now.Year(), now.Month(), now.Day(),
util.Config.NotifyByEmail.HourToTick, util.Config.NotifyByEmail.MinuteToTick, util.Config.NotifyByEmail.SecondToTick,
0, time.Local)
if nextTick.Before(now) {
nextTick = nextTick.Add(time.Duration(util.Config.NotifyByEmail.IntervalPeriodHour) * time.Hour)
}
beego.Warn("The next tick is", nextTick)
return nextTick.Sub(time.Now())
}

func NewEcsExsitTicker() *notifyTicker {
beego.Warn("new tick to monitor ecs before dawn")
return &notifyTicker{time.NewTimer(getNextTickDuration())}
}

func (jt *notifyTicker) UpdateJobTicker() bool {
ips, err := jt.getAllRunningPostPaidEcsInDB()
beego.Warn(ips)
if err != nil {
return false
}
isActive := jt.T.Reset(getNextTickDuration())
return isActive
}
已邀请:

fengche

赞同来自:

-0- 是不是在0点0分0秒跑了。

tom0001

赞同来自:

我用的简单的


//基础定时器为每小时,匹配hour触发动作
func Cron(h, m int) (<-chan time.Time, error) {
//因为只监控凌晨的时段,所以限定过滤器为0-5时
if h < 0 || h > 23 {
return nil, errors.New("hour must between 0 and 23")
}
if m < 0 || m > 59 {
return nil, errors.New("miniute mutst between 0 and 59")
}
var tick = time.Tick(1 * time.Minute)
var cron = make(chan time.Time)
go func() {
for now := range tick {
//send time to cron, when h, m matched
hour, min, _ := now.Clock()
if hour == h && m == min {
cron <- now
}
}
}()
return cron, nil
}

newer

赞同来自:

为什么不扔到 crontab 任务中, 要用程序来控制?

要回复问题请先登录注册