-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathScheduleInstant.cs
More file actions
64 lines (52 loc) · 2.25 KB
/
Copy pathScheduleInstant.cs
File metadata and controls
64 lines (52 loc) · 2.25 KB
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
using NCrontab;
using System;
using System.Collections.Generic;
using System.Linq;
namespace NetCoreStack.Jobs
{
internal class ScheduleInstant : IScheduleInstant
{
private readonly TimeZoneInfo _timeZone;
private readonly CrontabSchedule _schedule;
public static Func<CrontabSchedule, TimeZoneInfo, IScheduleInstant> Factory =
(schedule, timeZone) => new ScheduleInstant(DateTime.UtcNow, timeZone, schedule);
public ScheduleInstant(DateTime nowInstant, TimeZoneInfo timeZone, CrontabSchedule schedule)
{
if (nowInstant.Kind != DateTimeKind.Utc)
{
throw new ArgumentException("Only DateTime values in UTC should be passed.", nameof(nowInstant));
}
_timeZone = timeZone;
_schedule = schedule ?? throw new ArgumentNullException(nameof(schedule));
NowInstant = nowInstant.AddSeconds(-nowInstant.Second);
var nextOccurrences = _schedule.GetNextOccurrences(
TimeZoneInfo.ConvertTime(NowInstant, TimeZoneInfo.Utc, _timeZone),
DateTime.MaxValue);
foreach (var nextOccurrence in nextOccurrences)
{
if (_timeZone.IsInvalidTime(nextOccurrence)) continue;
NextInstant = TimeZoneInfo.ConvertTime(nextOccurrence, _timeZone, TimeZoneInfo.Utc);
break;
}
}
public ScheduleInstant()
{
}
public DateTime NowInstant { get; }
public DateTime? NextInstant { get; }
public IEnumerable<DateTime> GetNextInstants(DateTime lastInstant)
{
if (lastInstant.Kind != DateTimeKind.Utc)
{
throw new ArgumentException("Only DateTime values in UTC should be passed.", nameof(lastInstant));
}
return _schedule
.GetNextOccurrences(
TimeZoneInfo.ConvertTime(lastInstant, TimeZoneInfo.Utc, _timeZone),
TimeZoneInfo.ConvertTime(NowInstant.AddSeconds(1), TimeZoneInfo.Utc, _timeZone))
.Where(x => !_timeZone.IsInvalidTime(x))
.Select(x => TimeZoneInfo.ConvertTime(x, _timeZone, TimeZoneInfo.Utc))
.ToList();
}
}
}