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