Files
micro_layout/internal/runtime/crontab/crontab.go
T
2026-11-11 17:49:38 +08:00

78 lines
1.4 KiB
Go

package crontab
import (
"context"
"fmt"
"github.com/google/uuid"
"github.com/robfig/cron/v3"
"micro_layout/internal/runtime"
"micro_layout/pkg/util"
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: uuid.NewString(),
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().Done()
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
}