-
Notifications
You must be signed in to change notification settings - Fork 11
/
scheduler.go
52 lines (44 loc) · 1002 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 scheduler
import (
"context"
"sync"
"time"
)
type Job func(ctx context.Context)
type Scheduler struct {
wg *sync.WaitGroup
cancellations []context.CancelFunc
}
func NewScheduler() *Scheduler {
return &Scheduler{
wg: new(sync.WaitGroup),
cancellations: make([]context.CancelFunc, 0),
}
}
// Add starts goroutine which constantly calls provided job with interval delay
func (s *Scheduler) Add(ctx context.Context, j Job, interval time.Duration) {
ctx, cancel := context.WithCancel(ctx)
s.cancellations = append(s.cancellations, cancel)
s.wg.Add(1)
go s.process(ctx, j, interval)
}
// Stop cancels all running jobs
func (s *Scheduler) Stop() {
for _, cancel := range s.cancellations {
cancel()
}
s.wg.Wait()
}
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.wg.Done()
ticker.Stop()
return
}
}
}