reugn / go-quartz

Minimalist and zero-dependency scheduling library for Go
https://pkg.go.dev/github.com/reugn/go-quartz/quartz
MIT License
1.8k stars 85 forks source link

Day of week bug in CronTrigger.NextFireTime #11

Closed mykola-semenov closed 3 years ago

mykola-semenov commented 3 years ago

CronTrigger.NextFireTime produces wrong fire time when day of week in cron expression is smaller than current day of week.

Example:

package main

import (
    "fmt"
    "github.com/reugn/go-quartz/quartz"
    "time"
)

func main() {
    const dateLayout = "Mon Jan 2 15:04:05 2006"
    var currTime int64 = 1615363744528064087 // time.Now().UnixNano()
    fmt.Printf("Current time: %s\n\n", time.Unix(currTime/int64(time.Second), 0).UTC().Format(dateLayout))
    for i, dayOfWeek := range []string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"} {
        for _, dayOfWeekFormat := range []string{fmt.Sprint(i), dayOfWeek} {
            cronExpr := fmt.Sprintf("0 0 0 * * %s", dayOfWeekFormat)
            fmt.Println("Cron expression:", cronExpr)
            cronTrigger, err := quartz.NewCronTrigger(cronExpr)
            if err != nil {
                panic(err)
            }
            nextFireTime, err := cronTrigger.NextFireTime(currTime)
            if err != nil {
                panic(err)
            }
            fmt.Printf("Next fire time: %s\n\n", time.Unix(nextFireTime/int64(time.Second), 0).UTC().Format(dateLayout))
        }
    }
}

prints:

Current time: Wed Mar 10 08:09:04 2021

Cron expression: 0 0 0 * * 0
Next fire time: Wed Mar 17 00:00:00 2021

Cron expression: 0 0 0 * * Sun
Next fire time: Wed Mar 17 00:00:00 2021

Cron expression: 0 0 0 * * 1
Next fire time: Wed Mar 17 00:00:00 2021

Cron expression: 0 0 0 * * Mon
Next fire time: Wed Mar 17 00:00:00 2021

Cron expression: 0 0 0 * * 2
Next fire time: Wed Mar 17 00:00:00 2021

Cron expression: 0 0 0 * * Tue
Next fire time: Wed Mar 17 00:00:00 2021

Cron expression: 0 0 0 * * 3
Next fire time: Wed Mar 17 00:00:00 2021

Cron expression: 0 0 0 * * Wed
Next fire time: Wed Mar 17 00:00:00 2021

Cron expression: 0 0 0 * * 4
Next fire time: Thu Mar 11 00:00:00 2021

Cron expression: 0 0 0 * * Thu
Next fire time: Thu Mar 11 00:00:00 2021

Cron expression: 0 0 0 * * 5
Next fire time: Fri Mar 12 00:00:00 2021

Cron expression: 0 0 0 * * Fri
Next fire time: Fri Mar 12 00:00:00 2021

Cron expression: 0 0 0 * * 6
Next fire time: Sat Mar 13 00:00:00 2021

Cron expression: 0 0 0 * * Sat
Next fire time: Sat Mar 13 00:00:00 2021
reugn commented 3 years ago

@nikolai-semenov thank you for reporting that. The issue has been fixed in v0.3.4.