Custom Schedules

The underlying library supports a Schedule interface which allows for custom schedules to be implemented:

1type Schedule interface {
2    // Next returns the next activation time, later than the given time.
3    // Next is invoked initially, and then each time the job is run.
4    Next(time.Time) time.Time
5}

You can then create a type which implements this interface and, every time Next() is called return the time.Time when that job will execute.

To schedule the Job you then use the Schedule() function in the Service:

 1type MySchedule {
 2}
 3
 4func (s *MySchedule) Next(t time.Time) time.Time {
 5    return t.Add(time.Second*5)
 6}
 7
 8type MyJob struct {
 9}
10
11// Run will be called every 5 seconds
12func (j *MyJob) Run() {
13    // Do something
14}
15
16func (p *Example) Start() error {
17    id, err := p.cron.AddJob( &MySchedule{}, &MyJob{} )
18    if err != nil {
19        return err
20    }
21    p.tickId = id
22
23    return nil
24}
25
26func (p *Example) Stop() {
27    p.cron.Remove(p.tickId)
28}

The underlying library provides several Schedule implementations including ConstantDelaySchedule and SpecSchedule.

Last modified October 15, 2021: Switch print page breaks to css (d15ab85)