-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduler.go
78 lines (68 loc) · 1.36 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
package scheduler
import (
"fmt"
"log"
"sync"
"time"
)
// scheduler private struct
type scheduler struct {
f func()
quit chan struct{}
t *time.Ticker
}
// Scheduler map of schedulers
type Scheduler struct {
sync.Map
}
// New returns a new scheduler
func New() *Scheduler {
return &Scheduler{}
}
// AddScheduler calls a function every X defined interval
func (s *Scheduler) AddScheduler(name string, interval time.Duration, f func()) {
// create a new scheduler
task := scheduler{
f: f,
quit: make(chan struct{}),
t: time.NewTicker(interval),
}
// stop scheduler if exist
if sk, ok := s.Load(name); ok {
close(sk.(scheduler).quit)
}
// add a new task
s.Store(name, task)
// create the scheduler in a goroutine running forever until it quits
go func() {
for {
select {
case <-task.t.C:
task.f()
case <-task.quit:
task.t.Stop()
return
}
}
}()
}
// Stop ends and delete a specified scheduler.
func (s *Scheduler) Stop(name string) error {
sk, ok := s.Load(name)
if !ok {
return fmt.Errorf("Scheduler: %s, does not exist.", name)
}
close(sk.(scheduler).quit)
s.Delete(name)
return nil
}
// StopAll ends all schedulers.
func (s *Scheduler) StopAll() {
close := func(key, value interface{}) bool {
close(value.(scheduler).quit)
log.Printf("Stoping: %s", key)
s.Delete(key)
return true
}
s.Range(close)
}