2024-01-19 20:46:37 +00:00
|
|
|
package cron
|
|
|
|
|
|
|
|
import (
|
2024-01-28 07:20:59 +00:00
|
|
|
"context"
|
|
|
|
"go.uber.org/fx"
|
2024-01-19 20:46:37 +00:00
|
|
|
"go.uber.org/zap"
|
|
|
|
|
|
|
|
"github.com/go-co-op/gocron/v2"
|
|
|
|
)
|
|
|
|
|
2024-01-28 07:20:59 +00:00
|
|
|
type CronService interface {
|
|
|
|
Scheduler() gocron.Scheduler
|
|
|
|
RegisterService(service CronableService)
|
|
|
|
}
|
|
|
|
|
|
|
|
type CronableService interface {
|
|
|
|
LoadInitialTasks(cron CronService) error
|
|
|
|
}
|
|
|
|
|
|
|
|
type CronServiceParams struct {
|
|
|
|
fx.In
|
|
|
|
Logger *zap.Logger
|
|
|
|
Scheduler gocron.Scheduler
|
|
|
|
}
|
|
|
|
|
|
|
|
var Module = fx.Module("cron",
|
|
|
|
fx.Options(
|
|
|
|
fx.Provide(NewCronService),
|
2024-01-28 08:54:33 +00:00
|
|
|
fx.Provide(gocron.NewScheduler),
|
2024-01-28 07:20:59 +00:00
|
|
|
),
|
2024-01-19 20:46:37 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type CronServiceImpl struct {
|
|
|
|
scheduler gocron.Scheduler
|
2024-01-28 07:20:59 +00:00
|
|
|
services []CronableService
|
|
|
|
logger *zap.Logger
|
2024-01-19 20:46:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *CronServiceImpl) Scheduler() gocron.Scheduler {
|
|
|
|
return c.scheduler
|
|
|
|
}
|
|
|
|
|
2024-01-28 07:20:59 +00:00
|
|
|
func NewCronService(lc fx.Lifecycle, params CronServiceParams) *CronServiceImpl {
|
|
|
|
sc := &CronServiceImpl{
|
|
|
|
logger: params.Logger,
|
|
|
|
scheduler: params.Scheduler,
|
2024-01-20 17:05:41 +00:00
|
|
|
}
|
2024-01-19 20:46:37 +00:00
|
|
|
|
2024-01-28 07:20:59 +00:00
|
|
|
lc.Append(fx.Hook{
|
|
|
|
OnStart: func(ctx context.Context) error {
|
|
|
|
return sc.start()
|
|
|
|
},
|
|
|
|
})
|
2024-01-19 20:46:37 +00:00
|
|
|
|
2024-01-28 07:20:59 +00:00
|
|
|
return sc
|
2024-01-19 20:46:37 +00:00
|
|
|
}
|
|
|
|
|
2024-01-28 07:20:59 +00:00
|
|
|
func (c *CronServiceImpl) start() error {
|
2024-01-19 20:46:37 +00:00
|
|
|
for _, service := range c.services {
|
|
|
|
err := service.LoadInitialTasks(c)
|
|
|
|
if err != nil {
|
2024-01-28 07:20:59 +00:00
|
|
|
c.logger.Fatal("Failed to load initial tasks for service", zap.Error(err))
|
2024-01-19 20:46:37 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-20 17:18:43 +00:00
|
|
|
go c.scheduler.Start()
|
2024-01-20 16:48:10 +00:00
|
|
|
|
2024-01-19 20:46:37 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-01-28 07:20:59 +00:00
|
|
|
func (c *CronServiceImpl) RegisterService(service CronableService) {
|
2024-01-19 20:46:37 +00:00
|
|
|
c.services = append(c.services, service)
|
|
|
|
}
|