78 lines
1.4 KiB
Go
78 lines
1.4 KiB
Go
package crontab
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"git.xiaotuo.co/micro/skeleton/internal/runtime"
|
|
"git.xiaotuo.co/micro/skeleton/pkg/util"
|
|
"git.xiaotuo.co/pkg/tool/stringx"
|
|
"github.com/robfig/cron/v3"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
type Crontab struct {
|
|
options *runtime.Options
|
|
exit context.CancelFunc
|
|
}
|
|
|
|
func NewCrontab() *Crontab {
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
opts := &runtime.Options{
|
|
ID: stringx.MakeUUID(),
|
|
Type: "crontab",
|
|
Context: ctx,
|
|
}
|
|
return &Crontab{
|
|
options: opts,
|
|
exit: cancel,
|
|
}
|
|
}
|
|
|
|
func (m *Crontab) Init(opts ...runtime.Option) error {
|
|
for _, o := range opts {
|
|
o(m.options)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (m *Crontab) Start() error {
|
|
log.Infof("crontab %s Start...", m.String())
|
|
defer log.Infof("crontab Exit...")
|
|
|
|
c := cron.New(cron.WithSeconds())
|
|
|
|
// _, _ = c.AddJob("10/* * * * * *", Job(func() { // 每天 10s 执行
|
|
//
|
|
// }))
|
|
|
|
c.Start()
|
|
log.Infof("crontab start")
|
|
|
|
<-m.options.Context.Done()
|
|
log.Infof("crontab done")
|
|
c.Stop()
|
|
return nil
|
|
|
|
}
|
|
|
|
func (m *Crontab) Stop() error {
|
|
m.exit()
|
|
return nil
|
|
}
|
|
|
|
func (m *Crontab) String() string {
|
|
return fmt.Sprintf("%s://%s", m.options.Type, m.options.ID)
|
|
}
|
|
|
|
func Job(fn func()) cron.Job {
|
|
return cron.NewChain(cron.SkipIfStillRunning(cron.DefaultLogger)).Then(cron.FuncJob(fn))
|
|
}
|
|
|
|
func newContext() context.Context {
|
|
ctx := context.Background()
|
|
ctx = context.WithValue(ctx, "req_id", util.MakeRequestID())
|
|
return ctx
|
|
}
|