/
CrontabSchedule.cs
405 lines (339 loc) · 14.5 KB
/
CrontabSchedule.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
#region License and Terms
//
// NCrontab - Crontab for .NET
// Copyright (c) 2008 Atif Aziz. All rights reserved.
// Portions Copyright (c) 2001 The OpenSymphony Group. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace NCrontab
{
#region Imports
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Debug = System.Diagnostics.Debug;
#endregion
/// <summary>
/// Represents a schedule initialized from the crontab expression.
/// </summary>
// ReSharper disable once PartialTypeWithSinglePart
public sealed partial class CrontabSchedule
{
readonly CrontabField? _seconds;
readonly CrontabField _minutes;
readonly CrontabField _hours;
readonly CrontabField _days;
readonly CrontabField _months;
readonly CrontabField _daysOfWeek;
static readonly CrontabField SecondZero = CrontabField.Seconds("0");
// ReSharper disable once PartialTypeWithSinglePart
public sealed partial class ParseOptions
{
public bool IncludingSeconds { get; set; }
}
//
// Crontab expression format:
//
// * * * * *
// - - - - -
// | | | | |
// | | | | +----- day of week (0 - 6) (Sunday=0)
// | | | +------- month (1 - 12)
// | | +--------- day of month (1 - 31)
// | +----------- hour (0 - 23)
// +------------- min (0 - 59)
//
// Star (*) in the value field above means all legal values as in
// braces for that column. The value column can have a * or a list
// of elements separated by commas. An element is either a number in
// the ranges shown above or two numbers in the range separated by a
// hyphen (meaning an inclusive range).
//
// Source: http://www.adminschoice.com/docs/crontab.htm
//
// Six-part expression format:
//
// * * * * * *
// - - - - - -
// | | | | | |
// | | | | | +--- day of week (0 - 6) (Sunday=0)
// | | | | +----- month (1 - 12)
// | | | +------- day of month (1 - 31)
// | | +--------- hour (0 - 23)
// | +----------- min (0 - 59)
// +------------- sec (0 - 59)
//
// The six-part expression behaves similarly to the traditional
// crontab format except that it can denotate more precise schedules
// that use a seconds component.
//
public static CrontabSchedule Parse(string expression) => Parse(expression, null);
public static CrontabSchedule Parse(string expression, ParseOptions? options) =>
TryParse(expression, options, v => v, e => throw e());
public static CrontabSchedule? TryParse(string expression) => TryParse(expression, null);
public static CrontabSchedule? TryParse(string expression, ParseOptions? options) =>
TryParse(expression ?? string.Empty, options, v => v, _ => (CrontabSchedule?)null);
public static T TryParse<T>(string expression,
Func<CrontabSchedule, T> valueSelector,
Func<ExceptionProvider, T> errorSelector) =>
TryParse(expression ?? string.Empty, null, valueSelector, errorSelector);
public static T TryParse<T>(string expression, ParseOptions? options, Func<CrontabSchedule, T> valueSelector, Func<ExceptionProvider, T> errorSelector)
{
if (expression == null) throw new ArgumentNullException(nameof(expression));
var tokens = expression.Split(StringSeparatorStock.Space, StringSplitOptions.RemoveEmptyEntries);
var includingSeconds = options != null && options.IncludingSeconds;
var expectedTokenCount = includingSeconds ? 6 : 5;
if (tokens.Length < expectedTokenCount || tokens.Length > expectedTokenCount)
{
return errorSelector(() =>
{
var components =
includingSeconds
? "6 components of a schedule in the sequence of seconds, minutes, hours, days, months, and days of week"
: "5 components of a schedule in the sequence of minutes, hours, days, months, and days of week";
return new CrontabException($"'{expression}' is an invalid crontab expression. It must contain {components}.");
});
}
var fields = new CrontabField[6];
var offset = includingSeconds ? 0 : 1;
for (var i = 0; i < tokens.Length; i++)
{
var kind = (CrontabFieldKind)i + offset;
var field = CrontabField.TryParse(kind, tokens[i], v => new { ErrorProvider = (ExceptionProvider?)null, Value = (CrontabField?)v },
e => new { ErrorProvider = (ExceptionProvider?)e , Value = (CrontabField?)null }) ;
if (field.ErrorProvider != null)
return errorSelector(field.ErrorProvider);
fields[i + offset] = field.Value!; // non-null by mutual exclusivity!
}
return valueSelector(new CrontabSchedule(fields[0], fields[1], fields[2], fields[3], fields[4], fields[5]));
}
CrontabSchedule(
CrontabField? seconds,
CrontabField minutes, CrontabField hours,
CrontabField days, CrontabField months,
CrontabField daysOfWeek)
{
_seconds = seconds;
_minutes = minutes;
_hours = hours;
_days = days;
_months = months;
_daysOfWeek = daysOfWeek;
}
/// <summary>
/// Enumerates all the occurrences of this schedule starting with a
/// base time and up to an end time limit. This method uses deferred
/// execution such that the occurrences are only calculated as they
/// are enumerated.
/// </summary>
/// <remarks>
/// This method does not return the value of <paramref name="baseTime"/>
/// itself if it falls on the schedule. For example, if <paramref name="baseTime" />
/// is midnight and the schedule was created from the expression <c>* * * * *</c>
/// (meaning every minute) then the next occurrence of the schedule
/// will be at one minute past midnight and not midnight itself.
/// The method returns the <em>next</em> occurrence <em>after</em>
/// <paramref name="baseTime"/>. Also, <param name="endTime" /> is
/// exclusive.
/// </remarks>
public IEnumerable<DateTime> GetNextOccurrences(DateTime baseTime, DateTime endTime)
{
for (var occurrence = TryGetNextOccurrence(baseTime, endTime);
occurrence != null && occurrence < endTime;
occurrence = TryGetNextOccurrence(occurrence.Value, endTime))
{
yield return occurrence.Value;
}
}
/// <summary>
/// Gets the next occurrence of this schedule starting with a base time.
/// </summary>
public DateTime GetNextOccurrence(DateTime baseTime) =>
GetNextOccurrence(baseTime, DateTime.MaxValue);
/// <summary>
/// Gets the next occurrence of this schedule starting with a base
/// time and up to an end time limit.
/// </summary>
/// <remarks>
/// This method does not return the value of <paramref name="baseTime"/>
/// itself if it falls on the schedule. For example, if <paramref name="baseTime" />
/// is midnight and the schedule was created from the expression <c>* * * * *</c>
/// (meaning every minute) then the next occurrence of the schedule
/// will be at one minute past midnight and not midnight itself.
/// The method returns the <em>next</em> occurrence <em>after</em>
/// <paramref name="baseTime"/>. Also, <param name="endTime" /> is
/// exclusive.
/// </remarks>
public DateTime GetNextOccurrence(DateTime baseTime, DateTime endTime) =>
TryGetNextOccurrence(baseTime, endTime) ?? endTime;
DateTime? TryGetNextOccurrence(DateTime baseTime, DateTime endTime)
{
const int nil = -1;
var baseYear = baseTime.Year;
var baseMonth = baseTime.Month;
var baseDay = baseTime.Day;
var baseHour = baseTime.Hour;
var baseMinute = baseTime.Minute;
var baseSecond = baseTime.Second;
var endYear = endTime.Year;
var endMonth = endTime.Month;
var endDay = endTime.Day;
var year = baseYear;
var month = baseMonth;
var day = baseDay;
var hour = baseHour;
var minute = baseMinute;
var second = baseSecond + 1;
//
// Second
//
var seconds = _seconds ?? SecondZero;
second = seconds.Next(second);
if (second == nil)
{
second = seconds.GetFirst();
minute++;
}
//
// Minute
//
minute = _minutes.Next(minute);
if (minute == nil)
{
second = seconds.GetFirst();
minute = _minutes.GetFirst();
hour++;
}
else if (minute > baseMinute)
{
second = seconds.GetFirst();
}
//
// Hour
//
hour = _hours.Next(hour);
if (hour == nil)
{
minute = _minutes.GetFirst();
hour = _hours.GetFirst();
day++;
}
else if (hour > baseHour)
{
second = seconds.GetFirst();
minute = _minutes.GetFirst();
}
//
// Day
//
day = _days.Next(day);
RetryDayMonth:
if (day == nil)
{
second = seconds.GetFirst();
minute = _minutes.GetFirst();
hour = _hours.GetFirst();
day = _days.GetFirst();
month++;
}
else if (day > baseDay)
{
second = seconds.GetFirst();
minute = _minutes.GetFirst();
hour = _hours.GetFirst();
}
//
// Month
//
month = _months.Next(month);
if (month == nil)
{
second = seconds.GetFirst();
minute = _minutes.GetFirst();
hour = _hours.GetFirst();
day = _days.GetFirst();
month = _months.GetFirst();
year++;
}
else if (month > baseMonth)
{
second = seconds.GetFirst();
minute = _minutes.GetFirst();
hour = _hours.GetFirst();
day = _days.GetFirst();
}
//
// Stop processing when year is too large for the datetime or calendar
// object. Otherwise we would get an exception.
//
if (year > Calendar.MaxSupportedDateTime.Year)
return null;
//
// The day field in a cron expression spans the entire range of days
// in a month, which is from 1 to 31. However, the number of days in
// a month tend to be variable depending on the month (and the year
// in case of February). So a check is needed here to see if the
// date is a border case. If the day happens to be beyond 28
// (meaning that we're dealing with the suspicious range of 29-31)
// and the date part has changed then we need to determine whether
// the day still makes sense for the given year and month. If the
// day is beyond the last possible value, then the day/month part
// for the schedule is re-evaluated. So an expression like "0 0
// 15,31 * *" will yield the following sequence starting on midnight
// of Jan 1, 2000:
//
// Jan 15, Jan 31, Feb 15, Mar 15, Apr 15, Apr 31, ...
//
var dateChanged = day != baseDay || month != baseMonth || year != baseYear;
if (day > 28 && dateChanged && day > Calendar.GetDaysInMonth(year, month))
{
if (year >= endYear && month >= endMonth && day >= endDay)
return endTime;
day = nil;
goto RetryDayMonth;
}
var nextTime = new DateTime(year, month, day, hour, minute, second, 0, baseTime.Kind);
if (nextTime >= endTime)
return endTime;
//
// Day of week
//
if (_daysOfWeek.Contains((int)nextTime.DayOfWeek))
return nextTime;
return TryGetNextOccurrence(new DateTime(year, month, day, 23, 59, 59, 0, baseTime.Kind), endTime);
}
/// <summary>
/// Returns a string in crontab expression (expanded) that represents
/// this schedule.
/// </summary>
public override string ToString()
{
var writer = new StringWriter(CultureInfo.InvariantCulture);
if (_seconds != null)
{
_seconds.Format(writer, true);
writer.Write(' ');
}
_minutes.Format(writer, true); writer.Write(' ');
_hours.Format(writer, true); writer.Write(' ');
_days.Format(writer, true); writer.Write(' ');
_months.Format(writer, true); writer.Write(' ');
_daysOfWeek.Format(writer, true);
return writer.ToString();
}
static Calendar Calendar => CultureInfo.InvariantCulture.Calendar;
}
}