Skip to content

Commit

Permalink
Merge pull request #4 from dl1998/fix-stop-task
Browse files Browse the repository at this point in the history
Fix implementation of the StopTask method
  • Loading branch information
dl1998 authored Feb 27, 2024
2 parents 6b6bd66 + 059c8ce commit 094347b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
10 changes: 7 additions & 3 deletions pkg/scheduler/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,22 +199,26 @@ func (scheduler *Scheduler) ScheduleTask(name string, startTime *time.Time, dura
}

// StopTask encapsulates task stopping sequence.
func (scheduler *Scheduler) StopTask(task *Task) {
func (scheduler *Scheduler) StopTask(task *Task) error {
if task.stopSignal != nil {
close(task.stopSignal)
task.stopSignal = nil
}
scheduler.removeTask(task)
return scheduler.removeTask(task)
}

// removeTask removes Task from the tasks list of the Scheduler.
func (scheduler *Scheduler) removeTask(scheduledTask *Task) {
func (scheduler *Scheduler) removeTask(scheduledTask *Task) error {
taskIndex := scheduler.FindTaskIndex(scheduledTask)
if taskIndex == -1 {
return fmt.Errorf("task with id: %s cannot be stopped, because it was not found", scheduledTask.ID)
}
if len(scheduler.Tasks) <= 1 {
scheduler.Tasks = make([]*Task, 0)
} else {
scheduler.Tasks = append(scheduler.Tasks[:taskIndex], scheduler.Tasks[taskIndex+1:]...)
}
return nil
}

// callFunction calls a function dynamically using reflection.
Expand Down
22 changes: 20 additions & 2 deletions pkg/scheduler/scheduler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ func TestScheduler_StopTask(t *testing.T) {

time.Sleep(duration)

newScheduler.StopTask(newTask)
err := newScheduler.StopTask(newTask)

foundTask := false

Expand All @@ -307,11 +307,29 @@ func TestScheduler_StopTask(t *testing.T) {
}
}

if foundTask {
if foundTask && err != nil {
t.Fatalf("Task \"%s\" with id \"%s\" has not been stopped.", newTask.Name, newTask.ID)
}
}

// TestScheduler_StopTask_NotExist tests that Scheduler.StopTask method correctly
// handles situation where provided task doesn't exist.
func TestScheduler_StopTask_NotExist(t *testing.T) {
taskName := "Test Task"
intervalSeconds := 5
interval := time.Duration(intervalSeconds) * time.Second

newScheduler := CreateEmptyScheduler()
newTask := NewSimpleTask(taskName, interval)

err := newScheduler.StopTask(newTask)
expected := fmt.Sprintf("task with id: %s cannot be stopped, because it was not found", newTask.ID)

if err.Error() != expected {
t.Fatalf("Error has not been thrown for missing task with id %s.", newTask.ID)
}
}

// TestTask_GetFromContext tests that Task.GetFromContext method returns correct
// value from the Task.context based on the provided key.
func TestTask_GetFromContext(t *testing.T) {
Expand Down

0 comments on commit 094347b

Please sign in to comment.