common/pkg/cron/cron.go
2024-08-28 22:16:26 +08:00

56 lines
951 B
Go

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