-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepeat.go
More file actions
38 lines (35 loc) · 733 Bytes
/
repeat.go
File metadata and controls
38 lines (35 loc) · 733 Bytes
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
package repeat
import (
"context"
"sync"
"time"
)
// Run runs periodic calls of a function fn.
// It stops when the ctx is done.
func Run(ctx context.Context, period time.Duration, fn func(ctx context.Context)) {
ticker := time.NewTicker(period)
defer ticker.Stop()
for {
select {
case <-ticker.C:
fn(ctx)
case <-ctx.Done():
return
}
}
}
// Start starts periodic calls in a goroutine.
// Returns a function to stop that process.
func Start(period time.Duration, fn func(ctx context.Context)) (stop func()) {
ctx, ctxCancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
Run(ctx, period, fn)
}()
return func() {
ctxCancel()
wg.Wait()
}
}