Skip to content

Conversation

@CybotTM
Copy link
Member

@CybotTM CybotTM commented Nov 26, 2025

Summary

  • Add Clock type (func() time.Time) for custom time functions
  • Add WithClock Option to inject custom time source into Cron
  • Update now() method to use custom clock when configured
  • Add comprehensive tests for clock functionality

Motivation

Addresses #4 - Custom time source injection

Testing cron scheduling logic often requires control over time. The existing implementation always uses time.Now(), making tests either slow (waiting for real time) or requiring complex mocking.

This feature allows injecting a custom time source, enabling:

  • Deterministic tests with fixed timestamps
  • Fast-forwarding time in tests
  • Simulating specific dates/times for edge cases

Usage

// Fixed time for testing
fixedTime := time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC)
c := cron.New(cron.WithClock(func() time.Time { return fixedTime }))

// Or with controllable time
var currentTime atomic.Value
currentTime.Store(time.Now())
c := cron.New(cron.WithClock(func() time.Time { return currentTime.Load().(time.Time) }))

Test plan

  • TestWithClock - verify clock is set and used
  • TestWithClockAndLocation - verify clock respects location setting
  • TestWithClockNilFallback - verify default behavior when no clock set
  • All existing tests pass
  • Race detection passes
  • Linter passes

Closes #4

Add Clock type and WithClock functional option to allow injecting
a custom time source. This enables deterministic testing of
time-dependent cron behavior without waiting or mocking.

- Add Clock type as func() time.Time
- Add clock field to Cron struct
- Add WithClock Option with comprehensive documentation
- Update now() method to use custom clock when configured
- Add tests for clock, clock+location, and nil fallback

Closes #4
@CybotTM CybotTM merged commit 9eb150c into main Nov 26, 2025
14 checks passed
@CybotTM CybotTM deleted the feat/custom-clock branch November 26, 2025 13:16
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.

feat: add custom time source injection for testing

2 participants