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