feat 优化cron

This commit is contained in:
timerzz 2024-08-30 13:27:28 +08:00
parent bb8dde6361
commit a6be6c7cba

View File

@ -6,18 +6,19 @@ import (
) )
type Cron struct { type Cron struct {
time time.Time time time.Time
ctx context.Context ctx context.Context
f func() cancel context.CancelFunc
f func()
} }
func NewCron(ctx context.Context) *Cron { func NewCron() *Cron {
now := time.Now() now := time.Now()
l, _ := time.LoadLocation("Asia/Shanghai") l, _ := time.LoadLocation("Asia/Shanghai")
return &Cron{ c := &Cron{
ctx: ctx,
time: time.Date(now.Year(), now.Month(), now.Day(), 01, 0, 0, 0, l), time: time.Date(now.Year(), now.Month(), now.Day(), 01, 0, 0, 0, l),
} }
return c
} }
func (c *Cron) SetFunc(f func()) *Cron { func (c *Cron) SetFunc(f func()) *Cron {
@ -38,7 +39,8 @@ func (c *Cron) SetTimeHHmm(HHmm string) *Cron {
return c return c
} }
func (c *Cron) Run() { func (c *Cron) Run(ctx context.Context) {
c.ctx, c.cancel = context.WithCancel(ctx)
for { for {
if time.Now().After(c.time) { if time.Now().After(c.time) {
c.time = c.time.Add(time.Hour * 24) c.time = c.time.Add(time.Hour * 24)
@ -53,3 +55,7 @@ func (c *Cron) Run() {
} }
} }
} }
func (c *Cron) Stop() {
c.cancel()
}