-
Notifications
You must be signed in to change notification settings - Fork 0
/
fx.go
83 lines (74 loc) · 1.85 KB
/
fx.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
71
72
73
74
75
76
77
78
79
80
81
82
83
package golibcron
import (
"context"
"fmt"
"github.com/golibs-starter/golib"
"github.com/golibs-starter/golib/log"
"github.com/pkg/errors"
"go.uber.org/fx"
)
func Opt() fx.Option {
return fx.Options(
golib.ProvideProps(NewProperties),
golib.RegisterLogContextExtractor(ContextExtractor),
fx.Provide(NewDefaultRobfigCron),
fx.Invoke(RegisterJob),
fx.Invoke(StartCron),
)
}
func ProvideJob(jobConstructor interface{}) fx.Option {
return fx.Provide(fx.Annotated{Group: "cron_job", Target: jobConstructor})
}
type RegisterJobIn struct {
fx.In
Engine Engine
Jobs []Job `group:"cron_job"`
Props *Properties
}
func RegisterJob(in RegisterJobIn) error {
if len(in.Jobs) == 0 {
log.Infof("No cron jobs found to register")
return nil
}
log.Infof("Registering %d cron jobs", len(in.Jobs))
registeredCount := 0
for _, job := range in.Jobs {
jobName := GetJobName(job)
jobConfig, found := in.Props.GetJob(jobName)
if !found {
return fmt.Errorf("spec for job %s not found", jobName)
}
if jobConfig.Disabled {
log.Infof("Not-registered cron job [%s] due by job disabled", jobName)
continue
}
if err := in.Engine.AddJob(jobConfig.Spec, job); err != nil {
return errors.WithMessagef(err, "cannot register cron job %s with spec: %s", jobName, jobConfig.Spec)
}
registeredCount++
log.Infof("Registered cron job [%s] with spec [%s]", jobName, jobConfig.Spec)
}
log.Infof("Registered %d cron jobs", registeredCount)
return nil
}
func StartCron(c Engine) {
log.Infof("Cron Engine started")
c.StartAsync()
}
func OnStopHookOpt() fx.Option {
return fx.Invoke(OnStopHook)
}
type OnStopCronIn struct {
fx.In
Lc fx.Lifecycle
Cron Engine
}
func OnStopHook(in OnStopCronIn) {
in.Lc.Append(fx.Hook{
OnStop: func(ctx context.Context) error {
log.Infof("Receive stop signal for Cron Engine")
in.Cron.Stop()
return nil
},
})
}