From 990c12b3c1815c6b2414d4064636931c0d723d0b Mon Sep 17 00:00:00 2001 From: Jeremy Tregunna Date: Fri, 18 Apr 2025 15:46:43 -0600 Subject: [PATCH] feat: add context parameter to Task.Execute method --- README.md | 9 +++++---- task.go | 8 +++++--- task_test.go | 3 ++- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index a940c13..4677cc2 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ go get git.canoozie.net/jer/task package main import ( + "context" "fmt" "time" @@ -45,7 +46,7 @@ func (t *MyTask) ID() string { return t.TaskID } -func (t *MyTask) Execute() error { +func (t *MyTask) Execute(ctx context.Context) error { fmt.Printf("Executing task: %s\n", t.Name) return nil } @@ -135,13 +136,13 @@ To create a task, implement the `Task` interface: ```go type Task interface { ID() string - Execute() error + Execute(ctx context.Context) error Dependencies() []string } ``` - `ID()` - Returns a unique identifier for this task -- `Execute()` - Performs the task's operation, returning any errors +- `Execute(ctx context.Context)` - Performs the task's operation with context, returning any errors - `Dependencies()` - Returns a list of task IDs that must complete successfully before this task can run Any errors returned from `Execute()` will be logged and will prevent dependent tasks from running. @@ -154,7 +155,7 @@ Any errors returned from `Execute()` will be logged and will prevent dependent t ```go type Task interface { ID() string - Execute() error + Execute(ctx context.Context) error Dependencies() []string } ``` diff --git a/task.go b/task.go index 24a4349..a8cae69 100644 --- a/task.go +++ b/task.go @@ -1,6 +1,7 @@ package task import ( + "context" "log" "sync" "time" @@ -8,7 +9,7 @@ import ( type Task interface { ID() string - Execute() error + Execute(ctx context.Context) error Dependencies() []string } @@ -346,8 +347,9 @@ func (te *TaskExecutor) executeTask(st *ScheduledTask) { } te.completedTasksMutex.Unlock() - // Execute the task - err := st.task.Execute() + // Execute the task with a background context + ctx := context.Background() + err := st.task.Execute(ctx) // Update final task status te.completedTasksMutex.Lock() diff --git a/task_test.go b/task_test.go index 5056107..0009ad0 100644 --- a/task_test.go +++ b/task_test.go @@ -1,6 +1,7 @@ package task import ( + "context" "errors" "testing" "time" @@ -16,7 +17,7 @@ func (m *mockTask) ID() string { return m.id } -func (m *mockTask) Execute() error { +func (m *mockTask) Execute(ctx context.Context) error { return m.executeFunc() }