feat 添加cron
This commit is contained in:
parent
2dfacfbe2c
commit
95e8ec378f
55
pkg/cron/cron.go
Normal file
55
pkg/cron/cron.go
Normal file
@ -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
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user