@@ -8,17 +8,21 @@ import (
8
8
"time"
9
9
)
10
10
11
+ // Configuration options for creating a parser. Most options specify which
12
+ // fields should be included, while others enable features. If a field is not
13
+ // included the parser will assume a default value. These options do not change
14
+ // the order fields are parse in.
11
15
type ParseOption int
12
16
13
17
const (
14
- Second ParseOption = 1 << iota
15
- Minute
16
- Hour
17
- Dom
18
- Month
19
- Dow
20
- DowOptional
21
- Descriptor
18
+ Second ParseOption = 1 << iota // Seconds field, default 0
19
+ Minute // Minutes field, default 0
20
+ Hour // Hours field, default 0
21
+ Dom // Day of month field, default *
22
+ Month // Month field, default *
23
+ Dow // Day of week field, default *
24
+ DowOptional // Optional day of week field, default *
25
+ Descriptor // Allow descriptors such as @monthly, @weekly, etc.
22
26
)
23
27
24
28
var places = []ParseOption {
@@ -39,11 +43,26 @@ var defaults = []string{
39
43
"*" ,
40
44
}
41
45
46
+ // A custom Parser that can be configured.
42
47
type Parser struct {
43
48
options ParseOption
44
49
optionals int
45
50
}
46
51
52
+ // Creates a custom Parser with custom options.
53
+ //
54
+ // // Standard parser without descriptors
55
+ // specParser := NewParser(Minute | Hour | Dom | Month | Dow)
56
+ // sched, err := specParser.Parse("0 0 15 */3 *")
57
+ //
58
+ // // Same as above, just excludes time fields
59
+ // subsParser := NewParser(Dom | Month | Dow)
60
+ // sched, err := specParser.Parse("15 */3 *")
61
+ //
62
+ // // Same as above, just makes Dow optional
63
+ // subsParser := NewParser(Dom | Month | DowOptional)
64
+ // sched, err := specParser.Parse("15 */3")
65
+ //
47
66
func NewParser (options ParseOption ) Parser {
48
67
optionals := 0
49
68
if options & DowOptional > 0 {
@@ -53,6 +72,9 @@ func NewParser(options ParseOption) Parser {
53
72
return Parser {options , optionals }
54
73
}
55
74
75
+ // Parse returns a new crontab schedule representing the given spec.
76
+ // It returns a descriptive error if the spec is not valid.
77
+ // It accepts crontab specs and features configured by NewParser.
56
78
func (p Parser ) Parse (spec string ) (Schedule , error ) {
57
79
if spec [0 ] == '@' && p .options & Descriptor > 0 {
58
80
return parseDescriptor (spec )
@@ -74,9 +96,8 @@ func (p Parser) Parse(spec string) (Schedule, error) {
74
96
if count := len (fields ); count < min || count > max {
75
97
if min == max {
76
98
return nil , fmt .Errorf ("Expected exactly %d fields, found %d: %s" , min , count , spec )
77
- } else {
78
- return nil , fmt .Errorf ("Expected %d to %d fields, found %d: %s" , min , max , count , spec )
79
99
}
100
+ return nil , fmt .Errorf ("Expected %d to %d fields, found %d: %s" , min , max , count , spec )
80
101
}
81
102
82
103
// Fill in missing fields
0 commit comments