-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduler.go
95 lines (72 loc) · 1.82 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
86
87
88
89
90
91
92
93
94
95
package scheduler
import (
"context"
"fmt"
"reflect"
"sync"
"time"
)
type Scheduler struct {
cancels []context.CancelFunc
waitGroup *sync.WaitGroup
}
func NewScheduler() *Scheduler {
return &Scheduler{
cancels: []context.CancelFunc{},
waitGroup: &sync.WaitGroup{},
}
}
type ExecuteJobOptions struct {
Job any
Arguments []any
Timeout time.Duration
}
func (s *Scheduler) ExecuteJob(ctx context.Context, opts ExecuteJobOptions) error {
job, err := s.validateJob(opts.Job, opts.Arguments)
if err != nil {
return fmt.Errorf("failed to validate job: %w", err)
}
arguments := s.convertArgumentsToValues(opts.Arguments)
ctx, cancel := context.WithCancel(ctx)
s.cancels = append(s.cancels, cancel)
s.waitGroup.Add(1)
go s.startExecution(ctx, opts.Timeout, job, arguments)
return nil
}
func (s *Scheduler) Shutdown() {
for _, cancel := range s.cancels {
cancel()
}
s.waitGroup.Wait()
}
func (s *Scheduler) validateJob(job any, arguments []any) (reflect.Value, error) {
value := reflect.ValueOf(job)
if value.Kind() != reflect.Func {
return reflect.Value{}, fmt.Errorf("provided job is not a function")
}
numberOfArguments := value.Type().NumIn()
if numberOfArguments != len(arguments) {
return reflect.Value{}, fmt.Errorf("too few arguments provided")
}
return value, nil
}
func (s *Scheduler) convertArgumentsToValues(arguments []any) []reflect.Value {
values := make([]reflect.Value, len(arguments))
for _, argument := range arguments {
values = append(values, reflect.ValueOf(argument))
}
return values
}
func (s *Scheduler) startExecution(ctx context.Context, t time.Duration, j reflect.Value, args []reflect.Value) {
defer s.waitGroup.Done()
ticker := time.NewTicker(t)
defer ticker.Stop()
for {
select {
case <-ticker.C:
j.Call(args)
case <-ctx.Done():
return
}
}
}