Skip to content

Conversation

@sarsharma
Copy link

This PR uses https://github.com/benbjohnson/clock to mock the time.
Adding support for using mock clock with cron will be helpful to write test cases and verify cron behaviour.

Similar to this PR #327 but uses a more up to date mock clock

PR also contains fix for flaky unit tests on windows and minor linting fixes

Signed-off-by: Sarthak Sharma <sartsharma@microsoft.com>
Signed-off-by: Sarthak Sharma <sartsharma@microsoft.com>
Signed-off-by: Sarthak Sharma <sartsharma@microsoft.com>
Signed-off-by: Sarthak Sharma <sartsharma@microsoft.com>
@CybotTM
Copy link

CybotTM commented Dec 4, 2025

Solution available in maintained fork

This feature has been implemented in netresearch/go-cron, a maintained fork of this library.

Implementation: Full mock clock support with FakeClock that enables deterministic testing:

// Create a fake clock initialized to a specific time
fakeClock := cron.NewFakeClock(time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC))
c := cron.New(cron.WithClock(fakeClock))

// Add jobs as usual
c.AddFunc("@every 1h", func() {
    fmt.Println("Triggered!")
})

c.Start()

// Wait for scheduler to register timer
fakeClock.BlockUntil(1)

// Advance time deterministically - no real waiting!
fakeClock.Advance(time.Hour) // Triggers the job immediately

// Check timer count for assertions
count := fakeClock.TimerCount()

Features:

  • NewFakeClock(t) - Initialize to specific time
  • Advance(d) - Move time forward, firing expired timers
  • Set(t) - Jump to specific time
  • BlockUntil(n) - Wait for n timers to be registered
  • TimerCount() - Get active timer count

How to migrate:

// Change import from:
import "github.com/robfig/cron/v3"

// To:
import cron "github.com/netresearch/go-cron"

The API is 100% backward compatible. See the migration guide for details.

Related: netresearch#4, netresearch#34

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants