Kurt Peek
Kurt Peek

Reputation: 57791

How to start a cron job at regular intervals starting from a time in the past

I would like to build a program which runs a number of cron jobs which start at a time which, in general, is in the past. Here is a simplified example using gocron:

package main

import (
    "time"

    "github.com/jasonlvhit/gocron"
    "github.com/sirupsen/logrus"
)

// This slice would be obtained from persistent storage
var startTimes = []time.Time{
    time.Now().Add(-4 * time.Second),
    time.Now().Add(-3 * time.Second),
}

func format(t time.Time) string {
    return t.Format("15:04:05")
}

func notify(startTime time.Time) {
    logrus.WithField("time", format(time.Now())).Infof("I started at %s\n", format(startTime))
}

func main() {
    for _, startTime := range startTimes {
        gocron.Every(10).Seconds().From(&startTime).Do(notify, startTime)
    }

    logrus.Infof("Starting at %s...\n", format(time.Now()))
    <-gocron.Start()
}

If I run this, I get the following output:

INFO[0000] Starting at 00:30:54...                      
INFO[0010] I started at 00:30:50                         fields.time="00:31:04"
INFO[0010] I started at 00:30:51                         fields.time="00:31:04"

What I observe is that all the events are happening at once, 10 seconds after I start the program.

However, since the startTimes are 4 and 3 seconds before the program starts, what I would like is for the events to occur 6 and 7 seconds after the program starts (and every 10 seconds after that), respectively.

Is there a way to do this with gocron or some other tool?

Upvotes: 0

Views: 1218

Answers (2)

Adrian
Adrian

Reputation: 46602

This seems like just simple math:

    interval := 10 * time.Second
    nextTime := time.Now().Add((time.Since(startTime) + interval) % interval)
    gocron.Every(10).Seconds().From(&nextTime).Do(notify, nextTime)

https://play.golang.org/p/pwEZqy_LUuk

Upvotes: 2

ardhitama
ardhitama

Reputation: 1992

We can try to leverage a simple ticker, it is not a complete solution but should be easy enough to adapt.

package main

import (
    "fmt"
    "time"
)

func ticker(period time.Duration, length ...time.Duration) <-chan time.Time {
    ticker := time.NewTicker(period)

    if len(length) > 0 {
        done := make(chan bool)
        go func() {
            time.Sleep(period + length[0])
            done <- true
        }()

        go func() {
            <-done
            ticker.Stop()
        }()
    }

    return ticker.C

}

func main() {
    t1 := ticker(6*time.Second, 4*time.Second)
    t2 := ticker(7*time.Second, 3*time.Second)
    t3 := ticker(10 * time.Second)
    for {
        select {
        case t1 := <-t1:
            fmt.Println("t1: ", t1)
        case t2 := <-t2:
            fmt.Println("t2: ", t2)
        case t3 := <-t3:
            fmt.Println("t3: ", t3)
        }
    }
}

Upvotes: 1

Related Questions