Skip to content

Instantly share code, notes, and snippets.

@yangzh
Last active August 22, 2022 18:58
Show Gist options
  • Save yangzh/223241281794aa442950fff4013a3a58 to your computer and use it in GitHub Desktop.
Save yangzh/223241281794aa442950fff4013a3a58 to your computer and use it in GitHub Desktop.
mock time for gocron testing.
import (
"time"
"github.com/benbjohnson/clock"
)
type ClockTime struct {
clock.Clock
}
var _ gocron.TimeWrapper = ClockTime{}
func (ct ClockTime) Now(loc *time.Location) time.Time {
return ct.Clock.Now().In(loc)
}
func (ClockTime) Unix(sec, nsec int64) time.Time {
return time.Unix(sec, nsec)
}
func (ct ClockTime) Sleep(d time.Duration) {
ct.Clock.Sleep(d)
}
func TestSchedulerMock(t *testing.T) {
clock := clock.NewMock()
fmt.Printf("clock set at %s\n", clock.Now().UTC().Format(time.RFC3339))
s := gocron.NewScheduler(time.UTC)
s.CustomTime(ClockTime{clock})
var count int
_, err := s.Every(2).Second().DoWithJobDetails(func(job gocron.Job) {
fmt.Printf("next run: %s\n", job.NextRun())
count++
})
require.NoError(t, err)
s.StartAsync()
clock.Add(30 * time.Second)
for {
if count == 10 {
break
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment