cron icon indicating copy to clipboard operation
cron copied to clipboard

Next() returns wrong time when using cron.Parse()

Open jakexia72 opened this issue 3 years ago • 4 comments

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!

jakexia72 avatar Jun 16 '22 05:06 jakexia72

I think the first minute parameter cannot be *. The following example works for me.

new, _ := cron.Parse("0 */10 * * * *") // every 10th minute

pemako avatar Oct 26 '22 09:10 pemako

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 avatar Jan 20 '23 02:01 praveenprem

@praveenprem Start the cron and then check it.

c.Start() log.Printf("Next job: %s", c.Entry(eId).Next.String())

rajarathnabalan avatar Feb 14 '23 11:02 rajarathnabalan

@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.

praveenprem avatar Feb 14 '23 11:02 praveenprem