-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
scheduler.go
59 lines (46 loc) · 1.1 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
package scheduler
import (
"context"
"time"
"github.com/go-co-op/gocron"
"go.uber.org/fx"
"github.com/e154/smart-home/adaptors"
"github.com/e154/smart-home/common/logger"
)
var (
log = logger.MustGetLogger("scheduler")
)
type Scheduler struct {
adaptors *adaptors.Adaptors
scheduler *gocron.Scheduler
}
func NewScheduler(lc fx.Lifecycle,
adaptors *adaptors.Adaptors) (scheduler *Scheduler, err error) {
scheduler = &Scheduler{adaptors: adaptors}
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
return scheduler.Start(ctx)
},
OnStop: func(ctx context.Context) error {
return scheduler.Shutdown(ctx)
},
})
return
}
func (c *Scheduler) Start(_ context.Context) error {
c.scheduler = gocron.NewScheduler(time.UTC)
// every day at 00:00 am
_, _ = c.scheduler.Cron("0 0 * * *").Do(func() {
if err := c.adaptors.MetricBucket.DeleteOldest(60); err != nil {
log.Error(err.Error())
}
})
c.scheduler.StartAsync()
log.Info("started ...")
return nil
}
func (c *Scheduler) Shutdown(_ context.Context) error {
c.scheduler.Stop()
log.Info("shutdown ...")
return nil
}