29 lines
955 B
Go
29 lines
955 B
Go
package utils
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/robfig/cron/v3"
|
|
)
|
|
|
|
// cronParserWithSeconds 是一个自定义的 cron 解析器,它包含了秒字段。
|
|
// 这允许解析6部分的 cron 表达式(带秒),并处理 '?' 通配符。
|
|
var cronParserWithSeconds = cron.NewParser(
|
|
cron.Second | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor,
|
|
)
|
|
|
|
// GetNextCronTime 根据传入的 Cron 表达式计算下一次执行的时间。
|
|
// 它使用一个支持秒级精度和'?'通配符的解析器。
|
|
// 如果 Cron 表达式无效,它将返回一个错误。
|
|
func GetNextCronTime(cronExpression string) (time.Time, error) {
|
|
// 使用自定义的解析器来解析表达式
|
|
schedule, err := cronParserWithSeconds.Parse(cronExpression)
|
|
if err != nil {
|
|
return time.Time{}, err // 返回零值时间和错误
|
|
}
|
|
|
|
// 从当前时间计算下一次执行时间
|
|
nextTime := schedule.Next(time.Now())
|
|
return nextTime, nil
|
|
}
|