bitbucket.org/ai69/amoy@v0.2.3/run.go (about)

     1  package amoy
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"time"
     7  )
     8  
     9  var (
    10  	appStart = time.Now()
    11  
    12  	// ErrWaitTimeout indicates timeout after waiting.
    13  	ErrWaitTimeout = errors.New("amoy: wait timeout")
    14  )
    15  
    16  // AppUpTime returns time elapsed since the app started.
    17  func AppUpTime() time.Duration {
    18  	return time.Since(appStart)
    19  }
    20  
    21  // AppStartTime returns time when the app started.
    22  func AppStartTime() time.Time {
    23  	return appStart
    24  }
    25  
    26  // DelayRun waits for the duration to elapse and then calls task function, if it's not cancelled by the handler returns first.
    27  // It's like time.AfterFunc but returns context.CancelFunc instead of time.Timer.
    28  func DelayRun(interval time.Duration, task func()) context.CancelFunc {
    29  	ctx, cancel := context.WithCancel(context.Background())
    30  	go func(ctx context.Context) {
    31  		t := time.NewTimer(interval)
    32  		defer t.Stop()
    33  		select {
    34  		case <-t.C:
    35  			task()
    36  		case <-ctx.Done():
    37  		}
    38  	}(ctx)
    39  	return cancel
    40  }
    41  
    42  // RunWaitTimeout calls the task function, and waits for the result for the given max timeout.
    43  func RunWaitTimeout(timeout time.Duration, task func() error) error {
    44  	errCh := make(chan error)
    45  	go func() {
    46  		errCh <- task()
    47  	}()
    48  
    49  	t := time.NewTimer(timeout)
    50  	defer t.Stop()
    51  	select {
    52  	case <-t.C:
    53  		return ErrWaitTimeout
    54  	case err := <-errCh:
    55  		return err
    56  	}
    57  }