-
Notifications
You must be signed in to change notification settings - Fork 0
/
schedule.go
40 lines (34 loc) · 1011 Bytes
/
schedule.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
package swim
import (
"time"
"github.com/benbjohnson/clock"
)
// scheduleRepeaditly runs a function in the background continually with a
// dynamically computed delay in between invocations. The returned channels can
// be used to stop the background execution and a channel that will be unblocked
// when the background task is completely stopped.
//
// stop, wait := scheduleRepeaditly(func(){..}, func() time.Duration { return time.Second }, clock)
// time.sleep(time.Duration(10) * time.Second)
// // stop the background task
// close(stop)
// // wait till the background task is terminated
// <-wait
func scheduleRepeaditly(what func(), delayFn func() time.Duration, clock clock.Clock) (stop chan bool, wait <-chan bool) {
stop = make(chan bool)
internalWait := make(chan bool)
wait = internalWait
go func() {
defer close(internalWait)
for {
delay := delayFn()
what()
select {
case <-clock.After(delay):
case <-stop:
return
}
}
}()
return stop, wait
}