aboutsummaryrefslogtreecommitdiff
path: root/pkg/worker/worker.go
diff options
context:
space:
mode:
authorGabriel Arakaki Giovanini <mail@gabrielgio.me>2023-08-19 16:24:42 +0200
committerGabriel Arakaki Giovanini <mail@gabrielgio.me>2023-08-19 16:28:43 +0200
commitb242ed3c44f4dde7c4b452312b78a3b02f42ea65 (patch)
tree1a9cc1b68e4a94e530c5e2596c645a698c4a656e /pkg/worker/worker.go
parent84f80cdc4d27c3274c74f98255bf90c713e89a85 (diff)
downloadlens-b242ed3c44f4dde7c4b452312b78a3b02f42ea65.tar.gz
lens-b242ed3c44f4dde7c4b452312b78a3b02f42ea65.tar.bz2
lens-b242ed3c44f4dde7c4b452312b78a3b02f42ea65.zip
feat: Add task loop
Now the tasks will loop every given time. With this it will be able to pick up new photos after the application was started. I added 2h for file because my personal photo gallery is quite big and quite IO bottled necked so it tasks a lot of time to go through.
Diffstat (limited to 'pkg/worker/worker.go')
-rw-r--r--pkg/worker/worker.go62
1 files changed, 41 insertions, 21 deletions
diff --git a/pkg/worker/worker.go b/pkg/worker/worker.go
index 359384a..b768320 100644
--- a/pkg/worker/worker.go
+++ b/pkg/worker/worker.go
@@ -5,48 +5,68 @@ import (
"errors"
"fmt"
"sync"
+ "time"
)
type (
- // Worker should watch for context
- Worker interface {
+ // Task should watch for context
+ Task interface {
Start(context.Context) error
}
Work struct {
- Name string
- Worker Worker
+ Name string
+ Task Task
+ wait time.Duration
}
- WorkerPool struct {
- workers []*Work
+ TaskPool struct {
+ tasks []*Work
}
)
-func NewWorkerPool() *WorkerPool {
- return &WorkerPool{}
+func NewTaskPool() *TaskPool {
+ return &TaskPool{}
}
-func (self *WorkerPool) AddWorker(name string, worker Worker) {
- self.workers = append(self.workers, &Work{
- Name: name,
- Worker: worker,
+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 *WorkerPool) Start(ctx context.Context) {
+func (self *TaskPool) Start(ctx context.Context) {
var wg sync.WaitGroup
- wg.Add(len(self.workers))
+ wg.Add(len(self.tasks))
- for _, w := range self.workers {
+ for _, w := range self.tasks {
go func(w *Work) {
- defer wg.Done()
- if err := w.Worker.Start(ctx); err != nil && !errors.Is(err, context.Canceled) {
- fmt.Println("Processes finished, error", w.Name, err.Error())
- } else {
- fmt.Println(w.Name, "done")
- }
+ _ = w.run(ctx)
+ wg.Done()
}(w)
}