|
| 1 | +using System; |
| 2 | +using System.Threading; |
| 3 | +using NCrontab; |
| 4 | + |
| 5 | +public class CronTimer |
| 6 | +{ |
| 7 | + public const string UTC = "Etc/UTC"; |
| 8 | + |
| 9 | + static readonly TimeSpan InfiniteTimeSpan = TimeSpan.FromMilliseconds(Timeout.Infinite); // net 3.5 |
| 10 | + static readonly EventArgs ea = new EventArgs(); |
| 11 | + |
| 12 | + readonly CrontabSchedule schedule; |
| 13 | + readonly TimeZoneInfo tzi; |
| 14 | + readonly string id; |
| 15 | + Timer t; |
| 16 | + |
| 17 | + public string tz { get; } |
| 18 | + public string Expression { get; } |
| 19 | + public event EventHandler<EventArgs> OnOccurence; |
| 20 | + |
| 21 | + public CronTimer(string expression, string tz = UTC, bool includingSeconds = false) |
| 22 | + { |
| 23 | + Expression = expression; |
| 24 | + this.tz = tz; |
| 25 | + id = TimeZoneConverter.TZConvert.IanaToWindows(tz); |
| 26 | + tzi = TimeZoneInfo.FindSystemTimeZoneById(id); |
| 27 | + schedule = CrontabSchedule.Parse(expression, new CrontabSchedule.ParseOptions { IncludingSeconds = includingSeconds }); |
| 28 | + OnOccurence += OnOccurenceScheduleNext; |
| 29 | + } |
| 30 | + |
| 31 | + void OnOccurenceScheduleNext(object sender, EventArgs e) |
| 32 | + { |
| 33 | + var delay = CalculateDelay(); |
| 34 | + //Console.WriteLine($"Next for [{tz} {expression}] in {delay}."); |
| 35 | + t.Change(delay, InfiniteTimeSpan); |
| 36 | + } |
| 37 | + |
| 38 | + public void Start() |
| 39 | + { |
| 40 | + var delay = CalculateDelay(); |
| 41 | + //Console.WriteLine($"Next for [{tz} {expression}] in {delay}."); |
| 42 | + t = new Timer(s => OnOccurence(this, ea), null, delay, InfiniteTimeSpan); |
| 43 | + } |
| 44 | + |
| 45 | + TimeSpan CalculateDelay() |
| 46 | + { |
| 47 | + TimeSpan delay; |
| 48 | + if (tz != UTC) |
| 49 | + { |
| 50 | + var nowUtc = DateTime.UtcNow; |
| 51 | + var now = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, tzi); |
| 52 | + var next = schedule.GetNextOccurrence(now); |
| 53 | + var nextUtc = next.ToUniversalTime(); |
| 54 | + delay = nextUtc - nowUtc; |
| 55 | + } |
| 56 | + else |
| 57 | + { |
| 58 | + var nowUtc = DateTime.UtcNow; |
| 59 | + var nextUtc = schedule.GetNextOccurrence(nowUtc); |
| 60 | + delay = nextUtc - nowUtc; |
| 61 | + } |
| 62 | + //Console.WriteLine($"Now: {nowUtc} [utc] {now} [{tz}], Next: {next} [{tz}] {nextUtc} [utc], Delay: {delay}"); |
| 63 | + if (delay < TimeSpan.Zero) delay = TimeSpan.Zero; |
| 64 | + return delay; |
| 65 | + } |
| 66 | + |
| 67 | + public void Stop() |
| 68 | + { |
| 69 | + t.Dispose(); |
| 70 | + } |
| 71 | +} |
0 commit comments