Files
vHost/backend/internal/hosting/cron.go
T

96 lines
2.4 KiB
Go

package hosting
import (
"errors"
"strconv"
"strings"
"time"
_ "time/tzdata"
)
type Cron struct {
fields [5]map[int]bool
any [5]bool
location *time.Location
}
func ParseCron(expression, zone string) (Cron, error) {
var c Cron
loc, e := time.LoadLocation(zone)
if e != nil {
return c, errors.New("时区无效")
}
c.location = loc
parts := strings.Fields(expression)
if len(parts) != 5 {
return c, errors.New("计划时间需要五段:分钟 小时 日期 月份 星期")
}
mins := []int{0, 0, 1, 1, 0}
maxs := []int{59, 23, 31, 12, 7}
for i, part := range parts {
c.fields[i] = map[int]bool{}
c.any[i] = strings.HasPrefix(part, "*")
for _, piece := range strings.Split(part, ",") {
step := 1
rangePart := piece
if strings.Contains(piece, "/") {
items := strings.Split(piece, "/")
if len(items) != 2 {
return c, errors.New("计划时间格式无效")
}
rangePart = items[0]
step, e = strconv.Atoi(items[1])
if e != nil || step < 1 || step > 60 {
return c, errors.New("计划间隔无效")
}
}
start, end := mins[i], maxs[i]
if rangePart != "*" {
items := strings.Split(rangePart, "-")
if len(items) > 2 {
return c, errors.New("计划范围无效")
}
start, e = strconv.Atoi(items[0])
if e != nil {
return c, errors.New("计划时间只支持数字、星号、范围和步长")
}
end = start
if len(items) == 2 {
end, e = strconv.Atoi(items[1])
if e != nil {
return c, errors.New("计划范围无效")
}
}
}
if start < mins[i] || end > maxs[i] || start > end {
return c, errors.New("计划时间超出范围")
}
for n := start; n <= end; n += step {
value := n
if i == 4 && n == 7 {
value = 0
}
c.fields[i][value] = true
}
}
}
return c, nil
}
func (c Cron) Next(after time.Time) (time.Time, error) {
t := after.UTC().Truncate(time.Minute).Add(time.Minute)
for i := 0; i < 366*24*60; i++ {
local := t.In(c.location)
day := c.fields[2][local.Day()]
week := c.fields[4][int(local.Weekday())]
matchDay := day && week
if !c.any[2] && !c.any[4] {
matchDay = day || week
}
if c.fields[0][local.Minute()] && c.fields[1][local.Hour()] && c.fields[3][int(local.Month())] && matchDay {
return t, nil
}
t = t.Add(time.Minute)
}
return time.Time{}, errors.New("未来一年没有可执行时间")
}