-
Notifications
You must be signed in to change notification settings - Fork 1
/
Crontask.cs
314 lines (240 loc) · 7.82 KB
/
Crontask.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
using CronjobBase.args;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using CronjobBase.extensions;
using Microsoft.Win32;
namespace CronjobBase
{
public class Crontask : ICrontask
{
public enum eRunningType
{
/// <summary>
/// Daily on a specific time. (i.e. daily at 1 PM)
/// </summary>
daily = 0,
/// <summary>
/// One after one (i.e. after every 5 minutes)
/// </summary>
interval = 1,
/// <summary>
/// Interval (every 3 hours z.B.: 0, 3, 6, 9, 12, 15, 18, 21)
/// </summary>
absolute = 2,
/// <summary>
/// weekly on a specific day and time (z.b. sunday at 2 am).
/// </summary>
weekly = 3,
}
protected TimeSpan _duration { get; set; }
protected DayOfWeek _dayofWeek { get; set; }
protected DateTime? _lastrun { get; set; }
protected eRunningType _runningType { get; set; } = eRunningType.daily;
protected Timer _timer { get; set; }
private EventHandlerList __Events = new EventHandlerList();
private static object __evDoTask = new object();
private static object __evException = new object();
public bool CatchExceptions { get; set; } = true;
public bool StopOnException { get; set; } = false;
/// <summary>
/// Returns if this task is running.
/// </summary>
public bool IsRunning
{
get
{
return (_timer != null);
}
}
public virtual bool ShouldRun()
{
return true;
}
public Crontask()
{
CrontaskManager.RegisterTask(this);
}
public Crontask(TimeSpan duration, eRunningType runningType) : this()
{
this._duration = duration;
this._runningType = runningType;
}
public Crontask(int hours, int minutes, int seconds, eRunningType runningType) : this()
{
this._duration = new TimeSpan(hours, minutes, seconds);
this._runningType = runningType;
}
public Crontask(int hours, int minutes, int seconds, DayOfWeek weekDay, eRunningType runningType) : this()
{
this._duration = new TimeSpan(hours, minutes, seconds);
this._runningType = runningType;
this._dayofWeek = weekDay;
}
~Crontask()
{
CrontaskManager.UnregisterTask(this);
}
public void Start(bool doInitialRun = false)
{
if (_duration == null)
return;
if (doInitialRun)
{
InvokeAction();
return;
}
_timer = new Timer();
_timer.AutoReset = false;
_timer.Interval = CalculateInterval();
_timer.Elapsed += _timer_Elapsed;
_timer.Start();
}
public void InvokeAction()
{
_timer_Elapsed(null, null);
}
private double CalculateInterval()
{
if (this._runningType == eRunningType.interval)
{
return _duration.TotalMilliseconds;
}
if (this._runningType == eRunningType.daily)
{
var startDay = _lastrun?.Date ?? DateTime.Today;
var nextDay = startDay;
//Today already done? Search for tomorrow
if (startDay.Add(this._duration) <= DateTime.Now | (_lastrun != null && _lastrun?.Date == DateTime.Today))
{
nextDay = startDay.AddDays(1);
}
return (nextDay.Add(this._duration) - DateTime.Now).TotalMilliseconds;
}
if (this._runningType == eRunningType.absolute)
{
DateTime dt = DateTime.Now;
TimeSpan ts = dt.TimeOfDay;
TimeSpan tsNew = dt.TimeOfDay;
DateTime dtTarget = dt;
if (this._duration.Hours > 0)
{
tsNew = new TimeSpan(ts.Hours + this._duration.Hours, 0, 0);
dtTarget = DateTime.Today.Add(tsNew);
}
if (this._duration.Minutes > 0)
{
dtTarget = dtTarget.RoundUp(new TimeSpan(0, this._duration.Minutes, 0));
}
if (this._duration.Seconds > 0)
{
dtTarget = dtTarget.RoundUp(new TimeSpan(0, 0, this._duration.Seconds));
}
return (dtTarget - DateTime.Now).TotalMilliseconds;
}
if (this._runningType == eRunningType.weekly)
{
var nextDay = DateTimeExtensions.GetNextWeekday(DateTime.Now, this._dayofWeek).Date;
if (nextDay.Date == DateTime.Today)
nextDay = nextDay.AddDays(7);
var nextTime = nextDay.Add(_duration);
return (nextTime - DateTime.Now).TotalMilliseconds;
}
return 0;
}
private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (_timer != null)
_timer.Stop();
try
{
_lastrun = DateTime.Now;
if (ShouldRun())
{
OnDoTask(new EventArgs());
DoCronTask();
}
}
catch (Exception ex)
{
OnException(new ExceptionEventArgs(ex));
ExceptionRaised(ex);
if (!this.CatchExceptions)
throw ex;
//When enabled, stop on exception
if (this.StopOnException)
{
return;
}
}
//Restart
Start();
}
/// <summary>
/// Stops the task.
/// </summary>
public void Stop()
{
if (_timer == null)
return;
_timer.Stop();
_timer = null;
}
public event EventHandler DoTask
{
add
{
this.__Events.AddHandler(__evDoTask, value);
}
remove
{
this.__Events.RemoveHandler(__evDoTask, value);
}
}
private void OnDoTask(EventArgs e)
{
(__Events[__evDoTask] as EventHandler)?.Invoke(this, e);
}
public event EventHandler<ExceptionEventArgs> Exception
{
add
{
this.__Events.AddHandler(__evException, value);
}
remove
{
this.__Events.RemoveHandler(__evException, value);
}
}
private void OnException(ExceptionEventArgs e)
{
(__Events[__evException] as EventHandler<ExceptionEventArgs>)?.Invoke(this, e);
}
/// <summary>
/// Does a Task in sync
/// </summary>
public virtual void DoCronTask()
{
var task = DoAsyncCronTask();
task.GetAwaiter().GetResult();
}
/// <summary>
/// Does one or multiple tasks async and waites for completion.
/// </summary>
/// <returns></returns>
public virtual async Task DoAsyncCronTask()
{
}
public virtual void ExceptionRaised(Exception ex)
{
}
public void Log(String message)
{
Console.WriteLine(DateTime.Now.ToString() + " " + message);
}
}
}