-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathscheduler.go
52 lines (43 loc) · 898 Bytes
/
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
package main
import (
"fmt"
"time"
"sync"
"context"
)
type Job func(ctx context.Context)
type Scheduler struct {
group *sync.WaitGroup
cancellations []context.CancelFunc
}
func NewScheduler() *Scheduler {
return &Scheduler{
group: new(sync.WaitGroup),
cancellations: make([]context.CancelFunc, 0),
}
}
func (s *Scheduler) Add(ctx context.Context, j Job, interval time.Duration) {
ctx, cancel := context.WithCancel(ctx)
s.cancellations = append(s.cancellations, cancel)
s.group.Add(1)
go s.process(ctx, j, interval)
}
func (s *Scheduler) Stop() {
for _, cancel := range s.cancellations {
cancel()
}
s.group.Wait()
fmt.Println("stop called")
}
func (s *Scheduler) process(ctx context.Context, j Job, interval time.Duration) {
ticker := time.NewTicker(interval)
for {
select {
case <-ticker.C:
j(ctx)
case <-ctx.Done():
s.group.Done()
return
}
}
}