📄
MonitoringCheckScheduler.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
using Quartz; internal static class MonitoringCheckJobs { public const string JobGroup = "monitoring-checks"; public const string TriggerGroup = "monitoring-check-triggers"; public static JobKey JobKeyFor(int monitorId) => new($"check-{monitorId}", JobGroup); } internal sealed class MonitoringCheckScheduler(ISchedulerFactory schedulerFactory, ScreeningRepository repository) { public Task TriggerAsync(int monitorId, CancellationToken cancellationToken = default) => ScheduleCheckAsync(monitorId, force: true, cancellationToken); public async Task<int> TriggerAllAsync(CancellationToken cancellationToken = default) { var monitors = await repository.GetNonArchivedMonitoringsAsync(cancellationToken); foreach (var monitor in monitors) { await ScheduleCheckAsync(monitor.Id, force: true, cancellationToken); } return monitors.Count; } public async Task ScheduleRunningChecksAsync(CancellationToken cancellationToken = default) { var monitors = await repository.GetActiveMonitoringsAsync(cancellationToken); foreach (var monitor in monitors) { await ScheduleCheckAsync(monitor.Id, force: false, cancellationToken); } } private async Task ScheduleCheckAsync(int monitorId, bool force, CancellationToken cancellationToken) { var scheduler = await schedulerFactory.GetScheduler(cancellationToken); var jobKey = MonitoringCheckJobs.JobKeyFor(monitorId); if (!await scheduler.CheckExists(jobKey, cancellationToken)) { await scheduler.AddJob( JobBuilder .Create<CheckMonitoringJob>() .WithIdentity(jobKey) .UsingJobData("monitorId", monitorId) .StoreDurably() .RequestRecovery() .Build(), replace: true, cancellationToken ); } var trigger = TriggerBuilder .Create() .ForJob(jobKey) .WithIdentity(new TriggerKey($"{monitorId}-{Guid.NewGuid():N}", MonitoringCheckJobs.TriggerGroup)) .UsingJobData("force", force) .StartNow() .Build(); await scheduler.ScheduleJob(trigger, cancellationToken); } }