Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/mmccl5/go-task-task

go 1.22.5
44 changes: 26 additions & 18 deletions workspace/task/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import (
)

type Runner struct {
mu sync.RWMutex
tasks []*Task
mu sync.RWMutex
tasks []*Task
running bool
}

func NewRunner() *Runner {
Expand All @@ -24,10 +25,21 @@ func (r *Runner) AddTask(t *Task) {
}

func (r *Runner) Run(ctx context.Context) {
r.mu.RLock()
r.mu.Lock()
if r.running {
r.mu.Unlock()
return
}
r.running = true
tasks := make([]*Task, len(r.tasks))
copy(tasks, r.tasks)
r.mu.RUnlock()
r.mu.Unlock()

defer func() {
r.mu.Lock()
r.running = false
r.mu.Unlock()
}()

var wg sync.WaitGroup
for _, t := range tasks {
Expand All @@ -36,34 +48,30 @@ func (r *Runner) Run(ctx context.Context) {
defer wg.Done()

if ctx.Err() != nil {
task.mu.Lock()
task.State = StateFailed
task.Err = ctx.Err()
task.History = append(task.History, StateFailed)
task.mu.Unlock()
task.SetState(StateFailed)
task.SetErr(ctx.Err())
return
}

task.SetState(StateRunning)

task.mu.Lock()
task.State = StateRunning
task.StartedAt = time.Now()
task.History = append(task.History, StateRunning)
task.mu.Unlock()

err := task.Action(ctx)

task.mu.Lock()
task.FinishedAt = time.Now()
task.mu.Unlock()

if err != nil {
task.State = StateFailed
task.Err = err
task.History = append(task.History, StateFailed)
task.SetState(StateFailed)
task.SetErr(err)
} else {
task.State = StateCompleted
task.History = append(task.History, StateCompleted)
task.SetState(StateCompleted)
}
task.mu.Unlock()
}(t)
}
wg.Wait()
}
}