aboutsummaryrefslogtreecommitdiff
path: root/pkg/worker/worker.go
blob: b768320465871193d203467657b48372e7d2a0ba (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
package worker

import (
	"context"
	"errors"
	"fmt"
	"sync"
	"time"
)

type (
	// Task should watch for context
	Task interface {
		Start(context.Context) error
	}

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

	TaskPool struct {
		tasks []*Work
	}
)

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:
			fmt.Println("Process starting: ", w.Name)
			if err := w.Task.Start(ctx); err != nil && !errors.Is(err, context.Canceled) {
				fmt.Println("Process errored: ", w.Name, err.Error())
				return err
			} else {
				fmt.Println("Process done: ", w.Name)
			}
		}
		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) {
	var wg sync.WaitGroup

	wg.Add(len(self.tasks))

	for _, w := range self.tasks {
		go func(w *Work) {
			_ = w.run(ctx)
			wg.Done()
		}(w)
	}

	wg.Wait()
}