75 lines
1.4 KiB
Go
75 lines
1.4 KiB
Go
package job
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"github.com/robfig/cron/v3"
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
"nova_task/internal/job/earn"
|
|
"nova_task/internal/job/holder"
|
|
"nova_task/internal/job/stake_settle"
|
|
"nova_task/internal/svc"
|
|
)
|
|
|
|
// cronList 定时器Builder列表
|
|
var cronList = []func(context.Context, *svc.ServiceContext) cron.Job{
|
|
earn.NewCron,
|
|
holder.NewCron,
|
|
stake_settle.NewCron,
|
|
}
|
|
|
|
type Job struct {
|
|
ctx context.Context
|
|
cancel context.CancelFunc
|
|
svcCtx *svc.ServiceContext
|
|
c *cron.Cron
|
|
}
|
|
|
|
type Spec interface {
|
|
Spec() string
|
|
}
|
|
|
|
// NewJob 创建定时器服务
|
|
func NewJob(svcCtx *svc.ServiceContext) *Job {
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
var err error
|
|
c := cron.New(cron.WithSeconds())
|
|
for _, cf := range cronList {
|
|
cr := cf(ctx, svcCtx)
|
|
if cs, ok := cr.(Spec); ok {
|
|
spec := cs.Spec()
|
|
if spec == "" {
|
|
logx.Errorw("cron job spec is empty")
|
|
continue
|
|
}
|
|
_, err = c.AddJob(spec, cr)
|
|
logx.Must(err)
|
|
continue
|
|
}
|
|
|
|
if cs, ok := cr.(cron.Schedule); ok {
|
|
c.Schedule(cs, cr)
|
|
continue
|
|
}
|
|
logx.Must(errors.New("cron job must implement either Spec or Schedule interface"))
|
|
}
|
|
return &Job{
|
|
ctx: ctx,
|
|
cancel: cancel,
|
|
svcCtx: svcCtx,
|
|
c: c,
|
|
}
|
|
}
|
|
|
|
func (j *Job) Start() {
|
|
logx.Info("start cron job")
|
|
j.c.Start()
|
|
}
|
|
|
|
func (j *Job) Stop() {
|
|
logx.Info("stop cron job")
|
|
<-j.c.Stop().Done()
|
|
logx.Info("cron job stopped")
|
|
j.cancel()
|
|
}
|