github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/helper/slowmessage/slowmessage.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: MPL-2.0 3 4 package slowmessage 5 6 import ( 7 "time" 8 ) 9 10 // SlowFunc is the function that could be slow. Usually, you'll have to 11 // wrap an existing function in a lambda to make it match this type signature. 12 type SlowFunc func() error 13 14 // CallbackFunc is the function that is triggered when the threshold is reached. 15 type CallbackFunc func() 16 17 // Do calls sf. If threshold time has passed, cb is called. Note that this 18 // call will be made concurrently to sf still running. 19 func Do(threshold time.Duration, sf SlowFunc, cb CallbackFunc) error { 20 // Call the slow function 21 errCh := make(chan error, 1) 22 go func() { 23 errCh <- sf() 24 }() 25 26 // Wait for it to complete or the threshold to pass 27 select { 28 case err := <-errCh: 29 return err 30 case <-time.After(threshold): 31 // Threshold reached, call the callback 32 cb() 33 } 34 35 // Wait an indefinite amount of time for it to finally complete 36 return <-errCh 37 }