Skip to content

Commit a59e616

Browse files
Reasnoguxi.reasno
and
guxi.reasno
authored
feat: export NowFunc config to help tests (#242)
* feat: export NewFunc config to help tests Change-Id: I5be347f6de157380d963246f0c03d7c9ca9f4585 * feat: export NewFunc config to help tests Change-Id: Ibce615c1ce7fd486b65a5b691a140e82efad12ca Co-authored-by: guxi.reasno <[email protected]>
1 parent a05f3a3 commit a59e616

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

cron/config.go

+2
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,6 @@ type Config struct {
1616
GlobalOptions []JobOption
1717
// EnableSeconds is whether to enable seconds in the cron expression.
1818
EnableSeconds bool
19+
// NowFunc Allows the user to mock the current time.
20+
NowFunc func() time.Time
1921
}

cron/cron.go

+5
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ type Cron struct {
2323
location *time.Location
2424
nextID int
2525
quitWaiter sync.WaitGroup
26+
nowFunc func() time.Time
2627
}
2728

2829
// New returns a new Cron instance.
@@ -34,6 +35,7 @@ func New(config Config) *Cron {
3435
globalMiddleware: config.GlobalOptions,
3536
location: config.Location,
3637
nextID: 1,
38+
nowFunc: config.NowFunc,
3739
}
3840
if config.Parser == nil {
3941
if config.EnableSeconds {
@@ -173,6 +175,9 @@ func (c *Cron) Run(ctx context.Context) error {
173175
}
174176

175177
func (c *Cron) now() time.Time {
178+
if c.nowFunc != nil {
179+
return c.nowFunc()
180+
}
176181
return time.Now().In(c.location)
177182
}
178183

cron/cron_test.go

+23
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,26 @@ func TestCron_remove_job(t *testing.T) {
9292
case <-time.After(2 * time.Millisecond):
9393
}
9494
}
95+
96+
func TestCron_nowFunc(t *testing.T) {
97+
t.Parallel()
98+
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Millisecond)
99+
defer cancel()
100+
101+
fakeNow, _ := time.Parse("2006-01-02 15:04:05", "2019-01-01 00:00:00")
102+
c := New(Config{NowFunc: func() time.Time {
103+
return fakeNow.Add(-time.Microsecond)
104+
}})
105+
go c.Run(ctx)
106+
107+
ch := make(chan struct{})
108+
c.Add("0 0 * * *", func(ctx context.Context) error {
109+
ch <- struct{}{}
110+
return nil
111+
})
112+
select {
113+
case <-ch:
114+
case <-time.After(2 * time.Millisecond):
115+
t.Fatal("timeout")
116+
}
117+
}

0 commit comments

Comments
 (0)