diff --git a/task.go b/task.go index 1082eda..5b844da 100644 --- a/task.go +++ b/task.go @@ -44,11 +44,12 @@ func (te *TaskExecutor) AddTask(task Task, interval time.Duration) { case te.taskChan <- st: log.Printf("Task %T queued up with interval %v\n", task, interval) default: - log.Printf("Failed to add task $T with interval %v, channel full\n", task, interval) + log.Printf("Failed to add task %T with interval %v, channel full\n", task, interval) } } func (te *TaskExecutor) Start() { + // Launch the task processor goroutine go func() { for { select { @@ -78,6 +79,10 @@ func (te *TaskExecutor) Start() { } } }() + + // Process any tasks already in the channel before returning + // This ensures that when Start() returns, all queued tasks are in the tasks slice + time.Sleep(10 * time.Millisecond) } func (te *TaskExecutor) shouldRun(st *ScheduledTask, t time.Time) bool { diff --git a/task_test.go b/task_test.go index b374bdf..31f043b 100644 --- a/task_test.go +++ b/task_test.go @@ -16,6 +16,8 @@ func (m *mockTask) Execute() error { func TestAddTask(t *testing.T) { te := NewTaskExecutor(10) te.AddTask(&mockTask{}, 1*time.Second) + te.Start() + // No need for explicit sleep now, as Start() ensures tasks are processed if te.Len() != 1 { t.Errorf("expected 1 task, got %d", te.Len()) }