-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec-every.go
48 lines (45 loc) · 1.08 KB
/
exec-every.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
package core
import (
"time"
)
// ExecEvery runs a func as a go routine regularly
//
// returns 3 chans:
//
// - a chan to stop the time loop, pipe true
//
// - a chan to force the job execution on demand
//
// - a chan to change the ticker interval
//
// the invoked func can modify the interval by piping a new Duration to its given chan
//
// the func is executed once before the ticker starts
func ExecEvery(job func(tick int64, at time.Time, changeme chan time.Duration), every time.Duration) (chan bool, chan bool, chan time.Duration) {
changeme := make(chan time.Duration)
pingme := make(chan bool)
stopme := make(chan bool)
go func() {
tick := int64(0)
job(tick, time.Now(), changeme)
ticker := time.NewTicker(every)
for {
select {
case newtick := <-changeme:
if newtick > 0*time.Second {
ticker.Stop()
ticker = time.NewTicker(newtick)
}
case <-pingme:
job(tick, time.Now(), changeme)
case now := <-ticker.C:
tick++
job(tick, now, changeme)
case <-stopme:
ticker.Stop()
return
}
}
}()
return stopme, pingme, changeme
}