From c23c74e8b4fa12d2aeb1885bb5c7ed1249f7fdd4 Mon Sep 17 00:00:00 2001 From: Dmytro Leshchenko Date: Thu, 22 Feb 2024 22:48:36 +0100 Subject: [PATCH] Extend implementation with Wait method --- examples/basic/main.go | 2 +- pkg/scheduler/scheduler.go | 13 +++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) 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 + } +}