github.com/billybanfield/evergreen@v0.0.0-20170525200750-eeee692790f7/util/func.go (about)

     1  package util
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/pkg/errors"
     7  )
     8  
     9  var (
    10  	// ErrTimedOut is returned by a function that timed out.
    11  	ErrTimedOut = errors.New("Function timed out")
    12  )
    13  
    14  // RunFunctionWithTimeout runs a function, timing out after the specified time.
    15  // The error returned will be the return value of the function if it completes,
    16  // or ErrTimedOut if it times out.
    17  func RunFunctionWithTimeout(f func() error, timeout time.Duration) error {
    18  
    19  	// the error channel that the function's return value will be sent on
    20  	errChan := make(chan error)
    21  
    22  	// kick off the function
    23  	go func() {
    24  		errChan <- f()
    25  	}()
    26  
    27  	// wait, or timeout
    28  	var errResult error
    29  	select {
    30  	case errResult = <-errChan:
    31  		return errResult
    32  	case <-time.After(timeout):
    33  		return ErrTimedOut
    34  	}
    35  
    36  }