// Tests if jobs are starting before starting the scheduler. func TestStart_NoStart(test *testing.T) { sh := &Scheduler{} var wg sync.WaitGroup wg.Add(1) job1 := &counterJob{} job2 := &counterJob{} sh.Schedule("hello", job1, &t.When{Every: t.Every(200).Milliseconds()}) sh.Schedule("hi", job2, &t.When{Every: t.Every(100).Milliseconds()}) time.AfterFunc(300*time.Millisecond, func() { defer wg.Done() if job1.Count+job2.Count > 1 { test.Fatalf("scheduler not started but jobs have run") } }) wg.Wait() }
// Tests if repeating job is running on time. func TestSchedule_OntimeRepeating(test *testing.T) { sh := &Scheduler{} var wg sync.WaitGroup wg.Add(1) job := &counterJob{} sh.Schedule("hi", job, &t.When{Every: t.Every(100).Milliseconds()}) time.AfterFunc(300*time.Millisecond, func() { defer wg.Done() sh.Cancel("hi") if job.Count < 2 { test.Fatalf("scheduler worked for %v, expected to run 3 times", job.Count) } }) go sh.Start() wg.Wait() }
// Tests if jobs are being cancelled. func TestCancel(test *testing.T) { sh := &Scheduler{} var wg sync.WaitGroup wg.Add(1) job := &counterJob{} sh.Schedule("hi", job, &t.When{Every: t.Every(100).Milliseconds()}) time.AfterFunc(100*time.Millisecond, func() { defer wg.Done() sh.Cancel("hi") if job.Count > 2 { test.Fatalf("scheduler cancelled but job worked more than expected") } }) sh.Start() wg.Wait() }
// Tests if a job is being scheduled if it's registered after the start. func TestStart_AfterStart(test *testing.T) { sh := &Scheduler{} var wg sync.WaitGroup wg.Add(1) job := &counterJob{} sh.Start() sh.Schedule("hi", job, &t.When{Every: t.Every(100).Milliseconds()}) time.AfterFunc(300*time.Millisecond, func() { defer wg.Done() sh.Cancel("hi") if job.Count == 0 { test.Fatalf("job is expected to run even though it's scheduled after Start, but it didn't") } }) wg.Wait() }
// Tests if job is retried if it fails. func TestRetryCount(test *testing.T) { sh := &Scheduler{} var wg sync.WaitGroup wg.Add(1) job := &errorJob{errorAfter: 2} sh.ScheduleWithOpts("hi", job, &t.Opts{ RetryCount: 2, When: &t.When{Every: t.Every(100).Milliseconds()}, }) time.AfterFunc(200*time.Millisecond, func() { defer wg.Done() sh.Cancel("hi") if job.count < 2 { test.Fatalf("expected to retry for 2 times, ram %v times", job.count) } }) sh.Start() wg.Wait() }