portal/cron/cron.go

74 lines
1.3 KiB
Go
Raw Normal View History

2024-01-19 20:46:37 +00:00
package cron
import (
"context"
"go.uber.org/fx"
2024-01-19 20:46:37 +00:00
"go.uber.org/zap"
"github.com/go-co-op/gocron/v2"
)
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-19 20:46:37 +00:00
)
type CronServiceImpl struct {
scheduler gocron.Scheduler
services []CronableService
logger *zap.Logger
2024-01-19 20:46:37 +00:00
}
func (c *CronServiceImpl) Scheduler() gocron.Scheduler {
return c.scheduler
}
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
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
return sc.start()
},
})
2024-01-19 20:46:37 +00:00
return sc
2024-01-19 20:46:37 +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 {
c.logger.Fatal("Failed to load initial tasks for service", zap.Error(err))
2024-01-19 20:46:37 +00:00
}
}
go c.scheduler.Start()
2024-01-20 16:48:10 +00:00
2024-01-19 20:46:37 +00:00
return nil
}
func (c *CronServiceImpl) RegisterService(service CronableService) {
2024-01-19 20:46:37 +00:00
c.services = append(c.services, service)
}