robfig / cron

a cron library for go
MIT License
13.14k stars 1.63k forks source link

Supporting customize Timer to controll the scheduling behavior #491

Open cloudfly opened 1 year ago

cloudfly commented 1 year ago

Add a new interface Timer replace time.Timer for scheduling the job.

So that the user can create custom timer instead of using standard time.Timer,mainly used for testing。

eg.

import (
    "github.com/benbjohnson/clock"
        "github.com/robfig/cron/v3"
)

func main() {
    mockClock := clock.NewMock()
    cronEngine = cron.New(cron.WithTimerFunc(NewMockTimerFunc(mockClock)))
}

func NewMockTimerFunc(mock *clock.Mock) func(time.Duration) cron.Timer {
    return func(d time.Duration) cron.Timer {
        return &mockTimer{
            timer: mock.Timer(d),
        }
    }
}

type mockTimer struct {
    timer *clock.Timer
}

func (t *mockTimer) C() <-chan time.Time {
    return t.timer.C
}

func (t *mockTimer) Stop() bool {
    return t.timer.Stop()
}