From 95e8ec378fae7dda2c0d22dcab2ca6de54ef4347 Mon Sep 17 00:00:00 2001 From: timerzz Date: Wed, 28 Aug 2024 22:16:26 +0800 Subject: [PATCH] =?UTF-8?q?feat=20=E6=B7=BB=E5=8A=A0cron?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/cron/cron.go | 55 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 pkg/cron/cron.go diff --git a/pkg/cron/cron.go b/pkg/cron/cron.go new file mode 100644 index 0000000..3c3a649 --- /dev/null +++ b/pkg/cron/cron.go @@ -0,0 +1,55 @@ +package cron + +import ( + "context" + "time" +) + +type Cron struct { + time time.Time + ctx context.Context + f func() +} + +func NewCron(ctx context.Context) *Cron { + now := time.Now() + l, _ := time.LoadLocation("Asia/Shanghai") + return &Cron{ + ctx: ctx, + time: time.Date(now.Year(), now.Month(), now.Day(), 01, 0, 0, 0, l), + } +} + +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() + l, _ := time.LoadLocation("Asia/Shanghai") + c.time = time.Date(now.Year(), now.Month(), now.Day(), t.Hour(), t.Minute(), 0, 0, l) + return c +} + +func (c *Cron) Run() { + for { + if time.Now().After(c.time) { + c.time = c.time.Add(time.Hour * 24) + } + select { + case <-time.After(time.Until(c.time)): + if c.f != nil { + c.f() + } + case <-c.ctx.Done(): + return + } + } +}