-
Notifications
You must be signed in to change notification settings - Fork 411
/
Copy pathJobManager.cs
378 lines (325 loc) · 12.5 KB
/
JobManager.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
namespace FluentScheduler
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Controls the timer logic to execute all configured jobs.
/// </summary>
public static class JobManager
{
#region Internal fields
private static bool _useUtc = false;
private static Timer _timer = new Timer(state => ScheduleJobs(), null, Timeout.Infinite, Timeout.Infinite);
private static ScheduleCollection _schedules = new ScheduleCollection();
private static readonly ConcurrentDictionary<List<Action>, bool> _runningNonReentrant = new ConcurrentDictionary<List<Action>, bool>();
private static readonly ConcurrentDictionary<Guid, Schedule> _running = new ConcurrentDictionary<Guid, Schedule>();
private static DateTime Now
{
get
{
return _useUtc ? DateTime.UtcNow : DateTime.Now;
}
}
#endregion
#region Job factory
private static IJobFactory _jobFactory;
public static IJobFactory JobFactory
{
get
{
return (_jobFactory = _jobFactory ?? new JobFactory());
}
set
{
_jobFactory = value;
}
}
#endregion
#region Event handling
[SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly",
Justification = "Using strong-typed GenericEventHandler<TSender, TEventArgs> event handler pattern.")]
public static event GenericEventHandler<JobExceptionInfo, FluentScheduler.UnhandledExceptionEventArgs> JobException;
[SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly",
Justification = "Using strong-typed GenericEventHandler<TSender, TEventArgs> event handler pattern.")]
public static event GenericEventHandler<JobStartInfo, EventArgs> JobStart;
[SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly",
Justification = "Using strong-typed GenericEventHandler<TSender, TEventArgs> event handler pattern.")]
public static event GenericEventHandler<JobEndInfo, EventArgs> JobEnd;
private static void RaiseJobException(Schedule schedule, Task t)
{
var handler = JobException;
if (handler != null && t.Exception != null)
{
var info = new JobExceptionInfo
{
Name = schedule.Name,
Task = t
};
handler(info, new FluentScheduler.UnhandledExceptionEventArgs(t.Exception.InnerException, true));
}
}
private static void RaiseJobStart(Schedule schedule, DateTime startTime)
{
var handler = JobStart;
if (handler != null)
{
var info = new JobStartInfo
{
Name = schedule.Name,
StartTime = startTime
};
handler(info, new EventArgs());
}
}
private static void RaiseJobEnd(Schedule schedule, DateTime startTime, TimeSpan duration)
{
var handler = JobEnd;
if (handler != null)
{
var info = new JobEndInfo
{
Name = schedule.Name,
StartTime = startTime,
Duration = duration
};
if (schedule.NextRun != default(DateTime))
info.NextRun = schedule.NextRun;
handler(info, new EventArgs());
}
}
#endregion
#region Start, stop & initialize
/// <summary>
/// Initializes the job manager with all schedules configured in the specified registry
/// </summary>
/// <param name="registry">Registry containing job schedules</param>
public static void Initialize(Registry registry)
{
if (registry == null)
throw new ArgumentNullException("registry");
_useUtc = registry.UtcTime;
CalculateNextRun(registry.Schedules).ToList().ForEach(RunJob);
ScheduleJobs();
}
/// <summary>
/// Restarts the job manager if it had previously been stopped
/// </summary>
public static void Start()
{
ScheduleJobs();
}
/// <summary>
/// Stops the job manager from executing jobs.
/// </summary>
public static void Stop()
{
_timer.Change(Timeout.Infinite, Timeout.Infinite);
}
#endregion
#region Exposing schedules
/// <summary>
/// Get schedule by name.
/// </summary>
/// <param name="name">Schedule name</param>
/// <returns>Schedule instance or null if the schedule does not exist</returns>
public static Schedule GetSchedule(string name)
{
return _schedules.Get(name);
}
/// <summary>
/// Gets a list of currently schedules currently executing.
/// </summary>
public static IEnumerable<Schedule> RunningSchedules
{
get
{
return _running.Values.ToList();
}
}
/// <summary>
/// The list of all schedules, whether or not they are currently running.
/// Use <see cref="GetSchedule"/> to get concrete schedule by name.
/// </summary>
public static IEnumerable<Schedule> AllSchedules
{
get
{
return _schedules.All();
}
}
#endregion
#region Exposing adding & removing jobs (without the registry)
/// <summary>
/// Adds a job to the job manager
/// </summary>
/// <typeparam name="T">Job to schedule</typeparam>
/// <param name="jobSchedule">Schedule for the job</param>
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter",
Justification = "The 'T' requirement is on purpose.")]
public static void AddJob<T>(Action<Schedule> jobSchedule) where T : IJob
{
if (jobSchedule == null)
throw new ArgumentNullException("jobSchedule");
AddJob(jobSchedule, new Schedule(JobFactory.GetJobInstance<T>()) { Name = typeof(T).Name });
}
/// <summary>
/// Adds a job to the job manager
/// </summary>
/// <param name="jobAction">Job to schedule</param>
/// <param name="jobSchedule">Schedule for the job</param>
public static void AddJob(Action jobAction, Action<Schedule> jobSchedule)
{
if (jobSchedule == null)
throw new ArgumentNullException("jobSchedule");
AddJob(jobSchedule, new Schedule(jobAction));
}
private static void AddJob(Action<Schedule> jobSchedule, Schedule schedule)
{
jobSchedule(schedule);
CalculateNextRun(new Schedule[] { schedule }).ToList().ForEach(RunJob);
ScheduleJobs();
}
public static void RemoveJob(string name)
{
_schedules.Remove(name);
}
#endregion
#region Calculating, scheduling & running
private static IEnumerable<Schedule> CalculateNextRun(IEnumerable<Schedule> schedules)
{
foreach (var schedule in schedules)
{
if (schedule.CalculateNextRun == null)
{
if (schedule.DelayRunFor > TimeSpan.Zero)
{
// delayed job
schedule.NextRun = Now.Add(schedule.DelayRunFor);
_schedules.Add(schedule);
}
else
{
// run immediately
yield return schedule;
}
var hasAdded = false;
foreach (var child in schedule.AdditionalSchedules.Where(x => x.CalculateNextRun != null))
{
var nextRun = child.CalculateNextRun(Now.Add(child.DelayRunFor).AddMilliseconds(1));
if (!hasAdded || schedule.NextRun > nextRun)
{
schedule.NextRun = nextRun;
hasAdded = true;
}
}
}
else
{
schedule.NextRun = schedule.CalculateNextRun(Now.Add(schedule.DelayRunFor));
_schedules.Add(schedule);
}
foreach (var childSchedule in schedule.AdditionalSchedules)
{
if (childSchedule.CalculateNextRun == null)
{
if (childSchedule.DelayRunFor > TimeSpan.Zero)
{
// delayed job
childSchedule.NextRun = Now.Add(childSchedule.DelayRunFor);
_schedules.Add(childSchedule);
}
else
{
// run immediately
yield return childSchedule;
continue;
}
}
else
{
childSchedule.NextRun = childSchedule.CalculateNextRun(Now.Add(schedule.DelayRunFor));
_schedules.Add(childSchedule);
}
}
}
}
private static void ScheduleJobs()
{
_timer.Change(Timeout.Infinite, Timeout.Infinite);
_schedules.Sort();
if (!_schedules.Any())
return;
var firstJob = _schedules.First();
if (firstJob.NextRun <= Now)
{
RunJob(firstJob);
if (firstJob.CalculateNextRun == null)
{
// probably a ToRunNow().DelayFor() job, there's no CalculateNextRun
}
else
{
firstJob.NextRun = firstJob.CalculateNextRun(Now.AddMilliseconds(1));
}
if (firstJob.NextRun <= Now || firstJob.PendingRunOnce)
{
_schedules.Remove(firstJob);
}
firstJob.PendingRunOnce = false;
ScheduleJobs();
return;
}
var timerInterval = firstJob.NextRun - Now;
if (timerInterval <= TimeSpan.Zero)
{
ScheduleJobs();
return;
}
_timer.Change(timerInterval, timerInterval);
}
internal static void RunJob(Schedule schedule)
{
if (schedule.Disabled)
return;
if (!schedule.Reentrant)
{
if (!_runningNonReentrant.TryAdd(schedule.Jobs, true))
return;
}
var id = Guid.NewGuid();
_running.TryAdd(id, schedule);
var start = Now;
RaiseJobStart(schedule, start);
var task = Task.Factory.StartNew(() =>
{
var stopwatch = new Stopwatch();
try
{
stopwatch.Start();
foreach (var action in schedule.Jobs)
{
var subTask = Task.Factory.StartNew(action);
subTask.Wait();
}
}
finally
{
stopwatch.Stop();
bool notUsed;
_runningNonReentrant.TryRemove(schedule.Jobs, out notUsed);
Schedule notUsedSchedule;
_running.TryRemove(id, out notUsedSchedule);
RaiseJobEnd(schedule, start, stopwatch.Elapsed);
}
}, TaskCreationOptions.PreferFairness);
task.ContinueWith(t => RaiseJobException(schedule, t), TaskContinuationOptions.OnlyOnFaulted);
}
#endregion
}
}