Skip to content

Commit

Permalink
feat: export NowFunc config to help tests (#242)
Browse files Browse the repository at this point in the history
* 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 <guxi.reasno@bytedance.com>
  • Loading branch information
Reasno and guxi.reasno committed Jul 19, 2022
1 parent a05f3a3 commit a59e616
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
2 changes: 2 additions & 0 deletions cron/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@ type Config struct {
GlobalOptions []JobOption
// EnableSeconds is whether to enable seconds in the cron expression.
EnableSeconds bool
// NowFunc Allows the user to mock the current time.
NowFunc func() time.Time
}
5 changes: 5 additions & 0 deletions cron/cron.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ type Cron struct {
location *time.Location
nextID int
quitWaiter sync.WaitGroup
nowFunc func() time.Time
}

// New returns a new Cron instance.
Expand All @@ -34,6 +35,7 @@ func New(config Config) *Cron {
globalMiddleware: config.GlobalOptions,
location: config.Location,
nextID: 1,
nowFunc: config.NowFunc,
}
if config.Parser == nil {
if config.EnableSeconds {
Expand Down Expand Up @@ -173,6 +175,9 @@ func (c *Cron) Run(ctx context.Context) error {
}

func (c *Cron) now() time.Time {
if c.nowFunc != nil {
return c.nowFunc()
}
return time.Now().In(c.location)
}

Expand Down
23 changes: 23 additions & 0 deletions cron/cron_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,26 @@ func TestCron_remove_job(t *testing.T) {
case <-time.After(2 * time.Millisecond):
}
}

func TestCron_nowFunc(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Millisecond)
defer cancel()

fakeNow, _ := time.Parse("2006-01-02 15:04:05", "2019-01-01 00:00:00")
c := New(Config{NowFunc: func() time.Time {
return fakeNow.Add(-time.Microsecond)
}})
go c.Run(ctx)

ch := make(chan struct{})
c.Add("0 0 * * *", func(ctx context.Context) error {
ch <- struct{}{}
return nil
})
select {
case <-ch:
case <-time.After(2 * time.Millisecond):
t.Fatal("timeout")
}
}

0 comments on commit a59e616

Please sign in to comment.