Parse returns a new crontab schedule representing the given spec. It returns a descriptive error if the spec is not valid. It accepts crontab specs and features configured by NewParser.
(spec string)
| 86 | // It returns a descriptive error if the spec is not valid. |
| 87 | // It accepts crontab specs and features configured by NewParser. |
| 88 | func (p Parser) Parse(spec string) (Schedule, error) { |
| 89 | if len(spec) == 0 { |
| 90 | return nil, fmt.Errorf("empty spec string") |
| 91 | } |
| 92 | |
| 93 | // Extract timezone if present |
| 94 | var loc = time.Local |
| 95 | if strings.HasPrefix(spec, "TZ=") || strings.HasPrefix(spec, "CRON_TZ=") { |
| 96 | var err error |
| 97 | i := strings.Index(spec, " ") |
| 98 | eq := strings.Index(spec, "=") |
| 99 | if loc, err = time.LoadLocation(spec[eq+1 : i]); err != nil { |
| 100 | return nil, fmt.Errorf("provided bad location %s: %v", spec[eq+1:i], err) |
| 101 | } |
| 102 | spec = strings.TrimSpace(spec[i:]) |
| 103 | } |
| 104 | |
| 105 | // Handle named schedules (descriptors), if configured |
| 106 | if strings.HasPrefix(spec, "@") { |
| 107 | if p.options&Descriptor == 0 { |
| 108 | return nil, fmt.Errorf("parser does not accept descriptors: %v", spec) |
| 109 | } |
| 110 | return parseDescriptor(spec, loc) |
| 111 | } |
| 112 | |
| 113 | // Split on whitespace. |
| 114 | fields := strings.Fields(spec) |
| 115 | |
| 116 | // Validate & fill in any omitted or optional fields |
| 117 | var err error |
| 118 | fields, err = normalizeFields(fields, p.options) |
| 119 | if err != nil { |
| 120 | return nil, err |
| 121 | } |
| 122 | |
| 123 | field := func(field string, r bounds) uint64 { |
| 124 | if err != nil { |
| 125 | return 0 |
| 126 | } |
| 127 | var bits uint64 |
| 128 | bits, err = getField(field, r) |
| 129 | return bits |
| 130 | } |
| 131 | |
| 132 | var ( |
| 133 | second = field(fields[0], seconds) |
| 134 | minute = field(fields[1], minutes) |
| 135 | hour = field(fields[2], hours) |
| 136 | dayofmonth = field(fields[3], dom) |
| 137 | month = field(fields[4], months) |
| 138 | dayofweek = field(fields[5], dow) |
| 139 | ) |
| 140 | if err != nil { |
| 141 | return nil, err |
| 142 | } |
| 143 | |
| 144 | return &SpecSchedule{ |
| 145 | Second: second, |