github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/executor/executor.go (about)

     1  package executor
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  )
     7  
     8  type periodic struct {
     9  	refreshPeriod time.Duration
    10  	executionFunc func(context.Context)
    11  }
    12  
    13  // NewPeriodic creates a periodic executor, which calls given executionFunc periodically.
    14  func NewPeriodic(period time.Duration, executionFunc func(context.Context)) *periodic {
    15  	return &periodic{
    16  		refreshPeriod: period,
    17  		executionFunc: executionFunc,
    18  	}
    19  }
    20  
    21  // Run starts a periodic worker
    22  func (e *periodic) Run(ctx context.Context) {
    23  	go func() {
    24  		ticker := time.NewTicker(e.refreshPeriod)
    25  		for {
    26  			e.executionFunc(ctx)
    27  			select {
    28  			case <-ctx.Done():
    29  				ticker.Stop()
    30  				return
    31  			case <-ticker.C:
    32  			}
    33  		}
    34  	}()
    35  }