-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCronJobs.cs
71 lines (64 loc) · 2.38 KB
/
CronJobs.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
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Crestron.SimplSharp;
using Cronos;
using UXAV.Logging;
namespace UXAV.AVnet.Core
{
public static class CronJobs
{
private static readonly List<EventWaitHandle> Waits = new List<EventWaitHandle>();
static CronJobs()
{
CrestronEnvironment.ProgramStatusEventHandler += CrestronEnvironmentOnProgramStatusEventHandler;
}
private static void CrestronEnvironmentOnProgramStatusEventHandler(eProgramStatusEventType programEventType)
{
if (programEventType != eProgramStatusEventType.Stopping) return;
foreach (var waitHandle in Waits)
waitHandle.Set();
}
/// <summary>
/// Add a cronjob using a cron expression
/// </summary>
/// <param name="expression">Expression for the timing of the job</param>
/// <example>"30 07 * * 1-5" would equate to 07:30 on every day-of-week from Monday through Friday</example>
/// <param name="callback">Callback action when job is triggered</param>
/// <returns>Task</returns>
public static Task Add(string expression, Action callback)
{
var cronJob = CronExpression.Parse(expression);
return Task.Run(() =>
{
var waitHandle = CreateWaitHandle();
while (true)
{
var offset = cronJob.GetNextOccurrence(DateTimeOffset.UtcNow, TimeZoneInfo.Local);
if (offset == null) return;
var time = ((DateTimeOffset)offset).DateTime;
var waitTime = time - DateTime.Now;
//Logger.Debug($"Cronjob will wait for {waitTime:g}");
var signaled = waitHandle.WaitOne(waitTime);
if (signaled) return;
try
{
callback();
}
catch (Exception e)
{
Logger.Error(e);
}
Thread.Sleep(1000);
}
});
}
private static EventWaitHandle CreateWaitHandle()
{
var handle = new AutoResetEvent(false);
Waits.Add(handle);
return handle;
}
}
}