-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCronTimer.cs
77 lines (67 loc) · 2.24 KB
/
CronTimer.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
using System;
using System.Threading;
using NCrontab;
public class CronTimer
{
public const string UTC = "Etc/UTC";
static readonly TimeSpan InfiniteTimeSpan = TimeSpan.FromMilliseconds(Timeout.Infinite); // net 3.5
readonly CrontabSchedule schedule;
readonly TimeZoneInfo tzi;
readonly string id;
readonly Timer t;
public string tz { get; }
public string Expression { get; }
public event EventHandler<CronTimerEventArgs> OnOccurence;
public DateTime Next { get; private set; }
public CronTimer(string expression, string tz = UTC, bool includingSeconds = false)
{
Expression = expression;
this.tz = tz;
id = TimeZoneConverter.TZConvert.IanaToWindows(tz);
tzi = TimeZoneInfo.FindSystemTimeZoneById(id);
schedule = CrontabSchedule.Parse(expression, new CrontabSchedule.ParseOptions { IncludingSeconds = includingSeconds });
Next = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi);
OnOccurence += OnOccurenceScheduleNext;
t = new Timer(s =>
{
var ea = new CronTimerEventArgs
{
At = Next
};
OnOccurence(this, ea);
}, null, InfiniteTimeSpan, InfiniteTimeSpan);
}
void OnOccurenceScheduleNext(object sender, EventArgs e)
{
var delay = CalculateDelay();
//Console.WriteLine($"Next for [{tz} {expression}] in {delay}.");
t.Change(delay, InfiniteTimeSpan);
}
public void Start()
{
var delay = CalculateDelay();
//Console.WriteLine($"Next for [{tz} {expression}] in {delay}.");
t.Change(delay, InfiniteTimeSpan);
}
TimeSpan CalculateDelay()
{
var nowUtc = DateTime.UtcNow;
Next = schedule.GetNextOccurrence(Next);
TimeSpan delay;
if (tz != UTC)
{
delay = Next.ToUniversalTime() - nowUtc;
}
else
{
delay = Next - nowUtc;
}
//Console.WriteLine($"Now: {nowUtc} [utc] {now} [{tz}], Next: {next} [{tz}] {nextUtc} [utc], Delay: {delay}");
if (delay < TimeSpan.Zero) delay = TimeSpan.Zero;
return delay;
}
public void Stop()
{
t.Change(InfiniteTimeSpan, InfiniteTimeSpan);
}
}