Skip to content
This repository was archived by the owner on Aug 5, 2020. It is now read-only.

Commit 6aa120a

Browse files
authored
fix(jobs): run periodic jobs once at start time (#89)
a recent refactor of `DoPeriodic` (inadvertently) removed the initial invocation of a periodic job, and waited instead until the first frequency interval to execute. We want the first execution to be immediate. Includes updates to tests that verify expected job execution counts after definite time lapse periods.
1 parent 4e49625 commit 6aa120a

2 files changed

Lines changed: 15 additions & 5 deletions

File tree

jobs/jobs.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,12 +102,18 @@ func (u getLatestVersionData) Frequency() time.Duration {
102102
return u.frequency
103103
}
104104

105-
// DoPeriodic calls p.Do() every p.Frequency() on each element p in pSlice. For each p in pSlice,
106-
// a new goroutine is started, and the returned channel can be closed to stop all of the goroutines
105+
// DoPeriodic calls p.Do() once, and then again every p.Frequency() on each element p in pSlice.
106+
// For each p in pSlice, a new goroutine is started, and the returned channel can be closed
107+
// to stop all of the goroutines.
107108
func DoPeriodic(pSlice []Periodic) chan<- struct{} {
108109
doneCh := make(chan struct{})
109110
for _, p := range pSlice {
110111
go func(p Periodic) {
112+
// execute once at the beginning
113+
err := p.Do()
114+
if err != nil {
115+
log.Printf("periodic job ran and returned error (%s)", err)
116+
}
111117
ticker := time.NewTicker(p.Frequency())
112118
for {
113119
select {

jobs/jobs_test.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,14 @@ func (t testPeriodic) Frequency() time.Duration {
2525
}
2626

2727
func TestDoPeriodic(t *testing.T) {
28-
interval := time.Duration(100) * time.Millisecond
28+
interval := time.Duration(3000) * time.Millisecond
2929
p := &testPeriodic{t: t, err: nil, freq: interval}
3030
closeCh1 := DoPeriodic([]Periodic{p})
31-
time.Sleep(interval * 2)
32-
assert.True(t, p.i >= 1, "the periodic wasn't called at least once")
31+
time.Sleep(interval / 2) // wait a little while for the goroutine to call the job once
32+
assert.True(t, p.i == 1, "the periodic wasn't called once")
33+
time.Sleep(interval)
34+
assert.True(t, p.i == 2, "the periodic wasn't called twice")
35+
time.Sleep(interval)
36+
assert.True(t, p.i == 3, "the periodic wasn't called thrice")
3337
close(closeCh1)
3438
}

0 commit comments

Comments
 (0)