feat 优化cron

This commit is contained in:
timerzz 2024-08-30 13:27:28 +08:00
parent bb8dde6361
commit a6be6c7cba

View File

@ -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()
}