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 + } + } +}