daddy/cmd/server/scheduler.go

86 lines
1.7 KiB
Go
Raw Permalink Normal View History

package main
import (
"context"
"fmt"
"gitlab.com/wpetit/goweb/logger"
"forge.cadoles.com/Cadoles/daddy/internal/config"
"forge.cadoles.com/Cadoles/daddy/internal/task"
"github.com/pkg/errors"
"github.com/robfig/cron/v3"
)
type cronLogger struct {
ctx context.Context
}
func (l *cronLogger) Info(msg string, keysAndValues ...interface{}) {
fields := l.createFields(keysAndValues)
logger.Info(l.ctx, msg, fields...)
}
func (l *cronLogger) Error(err error, msg string, keysAndValues ...interface{}) {
fields := l.createFields(keysAndValues)
fields = append(fields, logger.E(err))
logger.Error(l.ctx, msg, fields...)
}
func (l *cronLogger) createFields(keysAndValues ...interface{}) []logger.Field {
fields := make([]logger.Field, 0)
var key string
for _, v := range keysAndValues {
children, ok := v.([]interface{})
if !ok {
continue
}
for i, vv := range children {
if i%2 == 0 {
key = fmt.Sprintf("%v", vv)
continue
}
fields = append(fields, logger.F(key, vv))
}
}
return fields
}
func runTaskScheduler(ctx context.Context, conf *config.Config) {
c := cron.New(
cron.WithLogger(&cronLogger{ctx}),
)
tasks := map[string]task.Task{
conf.Task.Newsletter.CronSpec: task.NewNewsletter(
ctx,
conf.Task.Newsletter.TimeRange,
conf.Task.Newsletter.BaseURL,
conf.Task.Newsletter.ContentTemplate,
conf.Task.Newsletter.SubjectTemplate,
conf.SMTP.SenderAddress,
),
}
for spec, task := range tasks {
if _, err := c.AddFunc(spec, task.Run); err != nil {
logger.Fatal(
ctx,
"could not schedule task",
logger.F("task", task.Name()),
logger.E(errors.WithStack(err)),
)
return
}
}
c.Start()
}