File tree 3 files changed +30
-0
lines changed
3 files changed +30
-0
lines changed Original file line number Diff line number Diff line change @@ -16,4 +16,6 @@ type Config struct {
16
16
GlobalOptions []JobOption
17
17
// EnableSeconds is whether to enable seconds in the cron expression.
18
18
EnableSeconds bool
19
+ // NowFunc Allows the user to mock the current time.
20
+ NowFunc func () time.Time
19
21
}
Original file line number Diff line number Diff line change @@ -23,6 +23,7 @@ type Cron struct {
23
23
location * time.Location
24
24
nextID int
25
25
quitWaiter sync.WaitGroup
26
+ nowFunc func () time.Time
26
27
}
27
28
28
29
// New returns a new Cron instance.
@@ -34,6 +35,7 @@ func New(config Config) *Cron {
34
35
globalMiddleware : config .GlobalOptions ,
35
36
location : config .Location ,
36
37
nextID : 1 ,
38
+ nowFunc : config .NowFunc ,
37
39
}
38
40
if config .Parser == nil {
39
41
if config .EnableSeconds {
@@ -173,6 +175,9 @@ func (c *Cron) Run(ctx context.Context) error {
173
175
}
174
176
175
177
func (c * Cron ) now () time.Time {
178
+ if c .nowFunc != nil {
179
+ return c .nowFunc ()
180
+ }
176
181
return time .Now ().In (c .location )
177
182
}
178
183
Original file line number Diff line number Diff line change @@ -92,3 +92,26 @@ func TestCron_remove_job(t *testing.T) {
92
92
case <- time .After (2 * time .Millisecond ):
93
93
}
94
94
}
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
+ }
You can’t perform that action at this time.
0 commit comments