github.com/prysmaticlabs/prysm@v1.4.4/shared/runutil/every.go (about) 1 // Package runutil includes helpers for scheduling runnable, periodic functions. 2 package runutil 3 4 import ( 5 "context" 6 "reflect" 7 "runtime" 8 "time" 9 10 log "github.com/sirupsen/logrus" 11 ) 12 13 // RunEvery runs the provided command periodically. 14 // It runs in a goroutine, and can be cancelled by finishing the supplied context. 15 func RunEvery(ctx context.Context, period time.Duration, f func()) { 16 funcName := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name() 17 ticker := time.NewTicker(period) 18 go func() { 19 for { 20 select { 21 case <-ticker.C: 22 log.WithField("function", funcName).Trace("running") 23 f() 24 case <-ctx.Done(): 25 log.WithField("function", funcName).Debug("context is closed, exiting") 26 ticker.Stop() 27 return 28 } 29 } 30 }() 31 }