backgroundTask runs task at the specified time interval in its own goroutine until stopped or an error is thrown by the BackgroundTaskFunc
(ctx context.Context, taskName string, task BackgroundTaskFunc, interval time.Duration, c chan bool)
| 23 | // backgroundTask runs task at the specified time interval in its own goroutine until stopped or an error is thrown by |
| 24 | // the BackgroundTaskFunc |
| 25 | func NewBackgroundTask(ctx context.Context, taskName string, task BackgroundTaskFunc, interval time.Duration, |
| 26 | c chan bool) (bgt BackgroundTask, err error) { |
| 27 | if interval <= 0 { |
| 28 | return BackgroundTask{}, &BackgroundTaskError{TaskName: taskName, Interval: interval} |
| 29 | } |
| 30 | bgt = BackgroundTask{ |
| 31 | taskName: taskName, |
| 32 | doneChan: make(chan struct{}), |
| 33 | } |
| 34 | |
| 35 | ctx = base.CorrelationIDLogCtx(ctx, taskName) |
| 36 | base.InfofCtx(ctx, base.KeyAll, "Created background task: %q with interval %v", taskName, interval) |
| 37 | go func() { |
| 38 | defer close(bgt.doneChan) |
| 39 | defer base.FatalPanicHandler() |
| 40 | ticker := time.NewTicker(interval) |
| 41 | defer ticker.Stop() |
| 42 | for { |
| 43 | select { |
| 44 | case <-ticker.C: |
| 45 | if err := task(ctx); err != nil { |
| 46 | base.ErrorfCtx(ctx, "Background task returned error: %v", err) |
| 47 | return |
| 48 | } |
| 49 | case <-c: |
| 50 | base.DebugfCtx(ctx, base.KeyAll, "Terminating background task") |
| 51 | return |
| 52 | } |
| 53 | } |
| 54 | }() |
| 55 | return bgt, nil |
| 56 | } |
| 57 | |
| 58 | type BackgroundTaskError struct { |
| 59 | TaskName string |
no test coverage detected