-
-
Save yangzh/223241281794aa442950fff4013a3a58 to your computer and use it in GitHub Desktop.
mock time for gocron testing.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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