File tree Expand file tree Collapse file tree
internal/exercises/templates/30_task_scheduler Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments