Debian Codegraph @

runutil/runutil.go

raw symbols SCIP
1 // Copyright (c) The EfficientGo Authors.
2 // Licensed under the Apache License 2.0.
3
4 // Initially copied from Thanos
5 //
6 // Copyright (c) The Thanos Authors.
7 // Licensed under the Apache License 2.0.
8
9 package runutil
10
11 import (
12 "time"
13 )
14
15 // Repeat executes f every interval seconds until stopc is closed or f returns an error.
16 // It executes f once right after being called.
17 func Repeat(interval time.Duration, stopc <-chan struct{}, f func() error) error {
18 tick := time.NewTicker(interval)
19 defer tick.Stop()
20
21 for {
22 if err := f(); err != nil {
23 return err
24 }
25 select {
26 case <-stopc:
27 return nil
28 case <-tick.C:
29 }
30 }
31 }
32
33 // Logger interface compatible with go-kit/logger.
34 type Logger interface {
35 Log(keyvals ...interface{}) error
36 }
37
38 // Retry executes f every interval seconds until timeout or no error is returned from f.
39 func Retry(interval time.Duration, stopc <-chan struct{}, f func() error) error {
40 return RetryWithLog(nil, interval, stopc, f)
41 }
42
43 // RetryWithLog executes f every interval seconds until timeout or no error is returned from f. It logs an error on each f error.
44 func RetryWithLog(logger Logger, interval time.Duration, stopc <-chan struct{}, f func() error) error {
45 tick := time.NewTicker(interval)
46 defer tick.Stop()
47
48 var err error
49 for {
50 if err = f(); err == nil {
51 return nil
52 }
53 if logger != nil {
54 _ = logger.Log("msg", "function failed. Retrying in next tick", "err", err)
55 }
56 select {
57 case <-stopc:
58 return err
59 case <-tick.C:
60 }
61 }
62 }