aboutsummaryrefslogtreecommitdiff
path: root/pkg/worker/worker.go
blob: 6b5c21cd67bc557b2b8bd1fa048229dc4b098efb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package worker

import (
	"context"
	"errors"
	"log/slog"
	"time"

	"golang.org/x/sync/errgroup"
)

type (
	Task interface {
		Start(context.Context) error
	}

	Work struct {
		Name string
		Task Task
		wait time.Duration
	}

	TaskPool struct {
		tasks []*Work
	}
)

const (
	format = "2006.01.02 15:04:05"
)

func NewTaskPool() *TaskPool {
	return &TaskPool{}
}

func (w *Work) run(ctx context.Context) error {
	// first time fire from the get go
	timer := time.NewTimer(time.Nanosecond)

	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-timer.C:
			if err := w.Task.Start(ctx); err != nil && !errors.Is(err, context.Canceled) {
				return err
			}
		}
		timer.Reset(w.wait)
	}
}

func (self *TaskPool) AddTask(name string, wait time.Duration, task Task) {
	self.tasks = append(self.tasks, &Work{
		Name: name,
		Task: task,
		wait: wait,
	})
}

func (self *TaskPool) Start(ctx context.Context) error {
	var g errgroup.Group

	for _, w := range self.tasks {
		g.Go(func(w *Work) func() error {
			return func() error {
				slog.Info("Process starting", "time", time.Now().Format(format), "name", w.Name)
				now := time.Now()
				if err := w.run(ctx); err != nil && !errors.Is(context.Canceled, err) {
					since := time.Since(now)
					slog.Error(
						"Process erred",
						"time", time.Now().Format(format),
						"name", w.Name,
						"error", err,
						"duration", since,
					)
					return err
				} else {
					since := time.Since(now)
					slog.Info(
						"Process ended",
						"time", time.Now().Format(format),
						"name", w.Name,
						"duration", since,
					)
				}
				return nil
			}
		}(w))
	}

	return g.Wait()
}