forked from healum/DigitalHealthCheck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathService.cs
99 lines (80 loc) · 2.89 KB
/
Service.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
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Timers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace DigitalHealthCheckService
{
public class Service
{
private readonly IServiceProvider serviceProvider;
private readonly ILogger<Service> logger;
public Service(IServiceProvider serviceProvider, ILogger<Service> logger, IConfiguration configuration)
{
this.serviceProvider = serviceProvider;
this.logger = logger;
logger.LogDebug("Starting work timer.");
if(!int.TryParse(configuration["TimerInterval"], out var timerInterval))
{
throw new InvalidOperationException("Cannot load configuration value for TimerInterval");
}
timer = new Timer { Interval = timerInterval };
timer.Elapsed += (sender, args) => RunTasks();
timer.Enabled = true;
logger.LogDebug("Work timer started successfully.");
}
bool inProgress;
private void RunTasks()
{
lock (this)
{
if (inProgress)
{
return;
}
inProgress = true;
}
logger.LogInformation($"Executing Digital Health Check background tasks, application version: {Assembly.GetExecutingAssembly().GetName().Version}");
try
{
var taskNumber = 1;
foreach (var task in Tasks)
{
logger.LogDebug($"Task #{taskNumber} :: {task.Header}");
try
{
task.Process().Wait();
}
catch (Exception ex)
{
logger.LogCritical("An error occurred when trying to run one of the schedule tasks", ex);
}
taskNumber++;
}
}
catch (Exception ex)
{
logger.LogCritical("An error occurred when trying to create one of the schedule tasks", ex);
}
finally
{
inProgress = false;
}
}
private static Timer timer;
IEnumerable<Task> Tasks
{
get
{
yield return serviceProvider.GetService<PatientFirstReminderEmail>();
yield return serviceProvider.GetService<PatientSecondReminderEmail>();
yield return serviceProvider.GetService<PatientSecondSurveyEmail>();
yield return serviceProvider.GetService<ThrivaNotificationEmail>();
}
}
public void Start() => timer.Start();
public void Stop() => timer.Stop();
}
}