common/pkg/cron/cron.go

63 lines
1.1 KiB
Go
Raw Normal View History

2024-08-28 22:16:26 +08:00
package cron
import (
"context"
"time"
2024-09-03 14:01:38 +08:00
"github.com/golang/glog"
2024-08-28 22:16:26 +08:00
)
type Cron struct {
2024-08-30 13:27:28 +08:00
time time.Time
ctx context.Context
cancel context.CancelFunc
f func()
2024-08-28 22:16:26 +08:00
}
2024-08-30 13:27:28 +08:00
func NewCron() *Cron {
2024-08-28 22:16:26 +08:00
now := time.Now()
2024-08-30 13:27:28 +08:00
c := &Cron{
2024-09-13 23:09:21 +08:00
time: time.Date(now.Year(), now.Month(), now.Day(), 01, 0, 0, 0, now.Location()),
2024-08-28 22:16:26 +08:00
}
2024-08-30 13:27:28 +08:00
return c
2024-08-28 22:16:26 +08:00
}
func (c *Cron) SetFunc(f func()) *Cron {
c.f = f
return c
}
func (c *Cron) SetContext(ctx context.Context) *Cron {
c.ctx = ctx
return c
}
func (c *Cron) SetTimeHHmm(HHmm string) *Cron {
t, _ := time.Parse("15:04", HHmm)
now := time.Now()
2024-09-13 23:11:33 +08:00
c.time = time.Date(now.Year(), now.Month(), now.Day(), t.Hour(), t.Minute(), 0, 0, now.Location())
2024-08-28 22:16:26 +08:00
return c
}
2024-08-30 13:27:28 +08:00
func (c *Cron) Run(ctx context.Context) {
c.ctx, c.cancel = context.WithCancel(ctx)
2024-08-28 22:16:26 +08:00
for {
if time.Now().After(c.time) {
c.time = c.time.Add(time.Hour * 24)
}
2024-09-03 14:01:38 +08:00
glog.Infof("cron 下次运行时间: %s", c.time)
2024-08-28 22:16:26 +08:00
select {
case <-time.After(time.Until(c.time)):
if c.f != nil {
c.f()
}
case <-c.ctx.Done():
return
}
}
}
2024-08-30 13:27:28 +08:00
func (c *Cron) Stop() {
c.cancel()
}