github.com/amazechain/amc@v0.1.3/utils/async.go (about) 1 package utils 2 3 import ( 4 "context" 5 "github.com/amazechain/amc/log" 6 "reflect" 7 "runtime" 8 "time" 9 ) 10 11 // RunEvery runs the provided command periodically. 12 // It runs in a goroutine, and can be cancelled by finishing the supplied context. 13 func RunEvery(ctx context.Context, period time.Duration, f func()) { 14 funcName := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name() 15 ticker := time.NewTicker(period) 16 go func() { 17 for { 18 select { 19 case <-ticker.C: 20 log.Trace("running", "function", funcName) 21 f() 22 case <-ctx.Done(): 23 log.Debug("context is closed, exiting", "function", funcName) 24 ticker.Stop() 25 return 26 } 27 } 28 }() 29 }