2024-08-28 22:16:26 +08:00
|
|
|
package cron
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Cron struct {
|
2024-08-30 13:27:28 +08:00
|
|
|
time time.Time
|
|
|
|
ctx context.Context
|
|
|
|
cancel context.CancelFunc
|
|
|
|
f func()
|
2024-08-28 22:16:26 +08:00
|
|
|
}
|
|
|
|
|
2024-08-30 13:27:28 +08:00
|
|
|
func NewCron() *Cron {
|
2024-08-28 22:16:26 +08:00
|
|
|
now := time.Now()
|
|
|
|
l, _ := time.LoadLocation("Asia/Shanghai")
|
2024-08-30 13:27:28 +08:00
|
|
|
c := &Cron{
|
2024-08-28 22:16:26 +08:00
|
|
|
time: time.Date(now.Year(), now.Month(), now.Day(), 01, 0, 0, 0, l),
|
|
|
|
}
|
2024-08-30 13:27:28 +08:00
|
|
|
return c
|
2024-08-28 22:16:26 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2024-08-30 13:27:28 +08:00
|
|
|
func (c *Cron) Run(ctx context.Context) {
|
|
|
|
c.ctx, c.cancel = context.WithCancel(ctx)
|
2024-08-28 22:16:26 +08:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-08-30 13:27:28 +08:00
|
|
|
|
|
|
|
func (c *Cron) Stop() {
|
|
|
|
c.cancel()
|
|
|
|
}
|