generated from ViBiOh/goweb
/
scheduler.go
70 lines (61 loc) · 1.81 KB
/
scheduler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package scheduler
import (
"context"
"flag"
"strings"
"syscall"
"time"
"github.com/ViBiOh/flags"
"github.com/ViBiOh/httputils/v4/pkg/cron"
"github.com/ViBiOh/httputils/v4/pkg/logger"
"github.com/ViBiOh/httputils/v4/pkg/redis"
"github.com/ViBiOh/ketchup/pkg/notifier"
"go.opentelemetry.io/otel/trace"
)
// App of package
type App interface {
Start(context.Context)
}
// Config of package
type Config struct {
enabled *bool
timezone *string
hour *string
}
type app struct {
tracer trace.Tracer
timezone string
hour string
redisApp redis.Client
notifierApp notifier.App
}
// Flags adds flags for configuring package
func Flags(fs *flag.FlagSet, prefix string) Config {
return Config{
enabled: flags.Bool(fs, prefix, "scheduler", "Enabled", "Enable cron job", true, nil),
timezone: flags.String(fs, prefix, "scheduler", "Timezone", "Timezone", "Europe/Paris", nil),
hour: flags.String(fs, prefix, "scheduler", "Hour", "Hour of cron, 24-hour format", "08:00", nil),
}
}
// New creates new App from Config
func New(config Config, notifierApp notifier.App, redisApp redis.Client, tracer trace.Tracer) App {
if !*config.enabled {
return nil
}
return app{
timezone: strings.TrimSpace(*config.timezone),
hour: strings.TrimSpace(*config.hour),
notifierApp: notifierApp,
redisApp: redisApp,
tracer: tracer,
}
}
func (a app) Start(ctx context.Context) {
cron.New().At(a.hour).In(a.timezone).Days().WithTracer(a.tracer).OnError(func(err error) {
logger.Error("error while running ketchup notify: %s", err)
}).OnSignal(syscall.SIGUSR1).Exclusive(a.redisApp, "ketchup:notify", 10*time.Minute).Start(ctx, func(ctx context.Context) error {
logger.Info("Starting ketchup notifier")
defer logger.Info("Ending ketchup notifier")
return a.notifierApp.Notify(ctx)
})
}