-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
85 lines (70 loc) · 1.69 KB
/
main.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 main
import (
"context"
"fmt"
"os"
"os/signal"
"sync"
"time"
)
// TODO: Add more TODOs
// TODO: Solve all the TODOs
// Job ...
type Job func(ctx context.Context)
// Scheduler ...
type Scheduler struct {
wg *sync.WaitGroup
cancellations []context.CancelFunc
}
// NewScheduler creates and return a New Scheduler object
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()
return
}
}
}
func main() {
ctx := context.Background()
worker := NewScheduler()
worker.Add(ctx, task1, time.Second*5)
worker.Add(ctx, task2, time.Second*10)
quit := make(chan os.Signal, 1)
// We can send multiple Interrupts. I think we should send interrupts = go routines spunned up.
signal.Notify(quit, os.Interrupt)
<-quit
worker.Stop()
}
func task1(ctx context.Context) {
// time.Sleep(time.Second * 1)
fmt.Printf("Task 1 done %s\n", time.Now().String())
}
func task2(ctx context.Context) {
// time.Sleep(time.Second * 1)
fmt.Printf("Task 2 done %s\n", time.Now().String())
}