-
Notifications
You must be signed in to change notification settings - Fork 62
/
scheduler.go
85 lines (76 loc) · 2.05 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package scheduler
import (
"context"
"fmt"
"sync"
k8upv1 "github.com/k8up-io/k8up/v2/api/v1"
"github.com/robfig/cron/v3"
controllerruntime "sigs.k8s.io/controller-runtime"
)
type (
// Scheduler handles all the schedules.
Scheduler struct {
cron *cron.Cron
schedules sync.Map
}
scheduleRef struct {
EntryID cron.EntryID
Schedule k8upv1.ScheduleDefinition
Runnable func(ctx context.Context)
}
SchedulerInterface interface {
HasSchedule(string) bool
SetSchedule(context.Context, string, k8upv1.ScheduleDefinition, func(ctx context.Context)) error
RemoveSchedule(context.Context, string)
}
)
var scheduler = newScheduler()
// GetScheduler returns the scheduler singleton instance.
func GetScheduler() *Scheduler {
return scheduler
}
func newScheduler() *Scheduler {
s := &Scheduler{
cron: cron.New(),
}
s.cron.Start()
return s
}
func (s *Scheduler) SetSchedule(ctx context.Context, key string, schedule k8upv1.ScheduleDefinition, fn func(ctx context.Context)) error {
existingRaw, exists := s.schedules.Load(key)
if exists {
s.cron.Remove(existingRaw.(*scheduleRef).EntryID)
}
id, err := s.cron.AddFunc(schedule.String(), func() {
runCtx := context.Background()
log := controllerruntime.LoggerFrom(runCtx).WithName("scheduler")
log.Info("Running schedule", "cron", schedule.String(), "key", key)
fn(runCtx)
})
if err != nil {
return fmt.Errorf("cannot set schedule: %w", err)
}
newRef := &scheduleRef{
EntryID: id,
Schedule: schedule,
Runnable: fn,
}
s.schedules.Store(key, newRef)
log := controllerruntime.LoggerFrom(ctx)
log.V(1).Info("Set schedule", "cron", newRef.Schedule, "key", key)
return nil
}
func (s *Scheduler) RemoveSchedule(ctx context.Context, key string) {
raw, loaded := s.schedules.LoadAndDelete(key)
if !loaded {
return
}
ref := raw.(*scheduleRef)
log := controllerruntime.LoggerFrom(ctx)
s.cron.Remove(ref.EntryID)
log.V(1).Info("Removed schedule", "cron", ref.Schedule, "key", key)
}
func (s *Scheduler) HasSchedule(key string) bool {
_, loaded := s.schedules.Load(key)
return loaded
}