diff --git a/examples/basic/main.go b/examples/basic/main.go index 2f267e2..5d24789 100644 --- a/examples/basic/main.go +++ b/examples/basic/main.go @@ -29,7 +29,7 @@ func main() { task := ScheduleDemoTask(*newScheduler) - time.Sleep(10 * time.Second) + task.Wait() fmt.Println() fmt.Println(task) diff --git a/pkg/scheduler/scheduler.go b/pkg/scheduler/scheduler.go index c4c0977..73195fa 100644 --- a/pkg/scheduler/scheduler.go +++ b/pkg/scheduler/scheduler.go @@ -177,7 +177,7 @@ func (scheduler *Scheduler) ScheduleTask(name string, startTime *time.Time, dura ticker := time.NewTicker(interval) defer ticker.Stop() - defer scheduler.removeTask(scheduledTask) + defer scheduler.StopTask(scheduledTask) for { select { @@ -200,7 +200,10 @@ func (scheduler *Scheduler) ScheduleTask(name string, startTime *time.Time, dura // StopTask encapsulates task stopping sequence. func (scheduler *Scheduler) StopTask(task *Task) { - close(task.stopSignal) + if task.stopSignal != nil { + close(task.stopSignal) + task.stopSignal = nil + } scheduler.removeTask(task) } @@ -246,3 +249,9 @@ func (task *Task) SetToContext(name string, value interface{}) { func (task *Task) RemoveFromContext(name string) { delete(task.context, name) } + +func (task *Task) Wait() { + if task.stopSignal != nil { + <-task.stopSignal + } +}