Next() returns wrong time when using cron.Parse()
When trying to get the next time that matches a schedule I've encountered some unexpected behaviour. Using a time that is close to a matching time returns the wrong next time. However, offsetting the time passed into Next() by one minute seems to be a workaround.
import (
"fmt"
"time"
"github.com/robfig/cron"
)
func main() {
new, _ := cron.Parse("* */10 * * * *") // every 10th minute
now := time.Unix(0, 0)
fmt.Println(now) // 1970-01-01 00:00:00 +0000 UTC
fmt.Println(new.Next(now)) // expect this to be 1970-10-00 00:00:00 +0000 UTC -> is actually 1970-01-01 00:00:01 +0000 UTC
test := now.Add(time.Minute) // advance by 1 minute
fmt.Println(test) // 1970-01-01 00:01:00 +0000 UTC
fmt.Println(new.Next(test)) // 1970-01-01 00:10:00 +0000 UTC -> which is correct
}
Let me know if I'm doing something wrong or if this is a bug. Thanks!
I think the first minute parameter cannot be *. The following example works for me.
new, _ := cron.Parse("0 */10 * * * *") // every 10th minute
I've found the exact same issue in v3 as well. It returns an invalid date. Documentation doesn't help with the situation being some of the functions on doc.go doesn't even exist on the code anymore.
package main
import (
"github.com/robfig/cron/v3"
"log"
"time"
)
func main() {
c := cron.New()
if eId, err := c.AddFunc("0 1 * * 1", func() {
log.Println("Job ran")
}); err != nil {
log.Fatalf("%#v", err)
} else {
log.Printf("PID: %d, job added", eId)
log.Printf("System time: %s", time.Now().String())
log.Printf("Next job: %s", c.Entry(eId).Next.String())
}
}
https://go.dev/play/p/d3tCBzKV-UC
Output
2009/11/10 23:00:00 PID: 1, job added
2009/11/10 23:00:00 System time: 2009-11-10 23:00:00 +0000 UTC m=+0.000000001
2009/11/10 23:00:00 Next job: 0001-01-01 00:00:00 +0000 UTC
Any idea what's going on here?
@praveenprem Start the cron and then check it.
c.Start()
log.Printf("Next job: %s", c.Entry(eId).Next.String())
@rajarathnabalan Thanks for taking the time to look into this. Go Playground seem to be working as expected, so I'll test it on my code as well.