Skip to content

Commit

Permalink
feat: add IsValidSpec()
Browse files Browse the repository at this point in the history
  • Loading branch information
fufuok committed Sep 19, 2024
1 parent 4c7c133 commit 229e9e0
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
21 changes: 21 additions & 0 deletions crontab/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package crontab

import (
"github.com/fufuok/cron"
)

// DefaultParser 等于 WithSecondOptional()
var DefaultParser = cron.NewParser(
cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor,
)

// IsValidSpec 检查定时任务标识是否有效
func IsValidSpec(spec string, parser ...cron.Parser) bool {
var err error
if len(parser) > 0 {
_, err = parser[0].Parse(spec)
} else {
_, err = DefaultParser.Parse(spec)
}
return err == nil
}
44 changes: 44 additions & 0 deletions crontab/utils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package crontab

import (
"testing"

"github.com/fufuok/cron"
"github.com/fufuok/utils/assert"
)

func TestIsValidSpec(t *testing.T) {
cases := []struct {
in string
ok bool
}{
{"* * * * *", true},
{"* * * * * *", true},
{"1 2 3 4 5 6", true},
{"0 */3 * * * *", true},
{"*/3 */3 2 * * *", true},
{"* * 1,15 * *", true},
{"* * */10 * Sun", true},
{"30 08 ? Jul Sun", true},
{"TZ=America/New_York 0 30 2 11 Mar ?", true},
{"CRON_TZ=America/New_York 0 0 * * * ?", true},

{"* * * *", false},
{"* * * * * * *", false},
{"61 * * * * *", false},
{"6 * 25 * * *", false},
{"6 * * 32 * *", false},
{"6 * * 3 13 *", false},
}
for _, c := range cases {
assert.Equal(t, c.ok, IsValidSpec(c.in), c.in)
}

standardParser := cron.NewParser(
cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor,
)
assert.Equal(t, true, IsValidSpec("1 2 3 4 5", standardParser))
assert.Equal(t, false, IsValidSpec("1 2 3 4 5 6", standardParser))
assert.Equal(t, true, IsValidSpec("1 2 3 4 5"))
assert.Equal(t, true, IsValidSpec("1 2 3 4 5 6"))
}

0 comments on commit 229e9e0

Please sign in to comment.