Skip to content

Commit 8583ba5

Browse files
Add solution for 30_task_scheduler exercise
1 parent ac5de84 commit 8583ba5

2 files changed

Lines changed: 49 additions & 0 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package taskscheduler
2+
3+
import "time"
4+
5+
// RunAfter runs a task once after the given delay.
6+
func RunAfter(delay time.Duration, task func()) {
7+
time.Sleep(delay)
8+
task()
9+
}
10+
11+
// RunEvery runs a task multiple times with the given delay between each run.
12+
func RunEvery(delay time.Duration, count int, task func()) {
13+
for i := 0; i < count; i++ {
14+
time.Sleep(delay)
15+
task()
16+
}
17+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package taskscheduler
2+
3+
import (
4+
"testing"
5+
"time"
6+
)
7+
8+
// TestRunAfter checks if the task runs exactly once after a short delay.
9+
func TestRunAfter(t *testing.T) {
10+
counter := 0
11+
12+
RunAfter(10*time.Millisecond, func() {
13+
counter++
14+
})
15+
16+
if counter != 1 {
17+
t.Errorf("expected task to run once, got %d", counter)
18+
}
19+
}
20+
21+
// TestRunEvery checks if the task runs the correct number of times.
22+
func TestRunEvery(t *testing.T) {
23+
counter := 0
24+
25+
RunEvery(5*time.Millisecond, 3, func() {
26+
counter++
27+
})
28+
29+
if counter != 3 {
30+
t.Errorf("expected task to run 3 times, got %d", counter)
31+
}
32+
}

0 commit comments

Comments
 (0)