Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions internal/exercises/templates/30_task_scheduler/task_scheduler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package taskscheduler

import "time"

// RunAfter runs a task once after the given delay.
func RunAfter(delay time.Duration, task func()) {
time.Sleep(delay)
task()
}
Comment thread
sidharth-chauhan marked this conversation as resolved.
Outdated

// RunEvery runs a task multiple times with the given delay between each run.
func RunEvery(delay time.Duration, count int, task func()) {
for i := 0; i < count; i++ {
time.Sleep(delay)
task()
}
}
Comment thread
sidharth-chauhan marked this conversation as resolved.
Outdated
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package taskscheduler

import (
"testing"
"time"
)

// TestRunAfter checks if the task runs exactly once after a short delay.
func TestRunAfter(t *testing.T) {
counter := 0

RunAfter(10*time.Millisecond, func() {
counter++
})

if counter != 1 {
t.Errorf("expected task to run once, got %d", counter)
}
}
Comment thread
sidharth-chauhan marked this conversation as resolved.
Outdated

// TestRunEvery checks if the task runs the correct number of times.
func TestRunEvery(t *testing.T) {
counter := 0

RunEvery(5*time.Millisecond, 3, func() {
counter++
})

if counter != 3 {
t.Errorf("expected task to run 3 times, got %d", counter)
}
}
Comment thread
sidharth-chauhan marked this conversation as resolved.
Outdated
Loading