From a6be6c7cbab3a6a6e67c0e06a26836ad5413e47c Mon Sep 17 00:00:00 2001 From: timerzz Date: Fri, 30 Aug 2024 13:27:28 +0800 Subject: [PATCH] =?UTF-8?q?feat=20=E4=BC=98=E5=8C=96cron?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/cron/cron.go | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) 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() +}