86 lines
2.7 KiB
C#
86 lines
2.7 KiB
C#
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
using ProperDI.Azure.Endpoints.ResourceGroup.LogLooker;
|
|
|
|
public class RoleAssesorBackgroundService : IHostedService, IDisposable
|
|
{
|
|
private readonly IActivityLogReader _activityLogReader;
|
|
private readonly ILogger<RoleAssesorBackgroundService> _logger;
|
|
private readonly IOptionsMonitor<RoleAssesorBackgroundServiceOptions> _options;
|
|
private Timer? _timer;
|
|
private int _runFrequencyInMinutes;
|
|
|
|
public RoleAssesorBackgroundService(
|
|
IActivityLogReader activityLogReader,
|
|
ILogger<RoleAssesorBackgroundService> logger,
|
|
IOptionsMonitor<RoleAssesorBackgroundServiceOptions> options)
|
|
{
|
|
_activityLogReader = activityLogReader;
|
|
_logger = logger;
|
|
_options = options;
|
|
|
|
// This sets our initial run frequency
|
|
_runFrequencyInMinutes = _options.CurrentValue.RunFrequencyInMinutes;
|
|
|
|
// Subscribe to any changes in the config file
|
|
_options.OnChange(UpdateTimerInterval);
|
|
}
|
|
|
|
private void UpdateTimerInterval(RoleAssesorBackgroundServiceOptions options)
|
|
{
|
|
var newFreq = options.RunFrequencyInMinutes;
|
|
|
|
if (newFreq == _runFrequencyInMinutes)
|
|
return;
|
|
|
|
_runFrequencyInMinutes = newFreq;
|
|
_logger.LogInformation("Run frequency updated to {RunFreq} minutes", _runFrequencyInMinutes);
|
|
_timer?.Change(TimeSpan.Zero, TimeSpan.FromMinutes(_runFrequencyInMinutes));
|
|
}
|
|
|
|
public Task StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
_logger.LogInformation("Role Assessor background service is starting.");
|
|
|
|
_timer = new Timer(async _ => await ProcessAsync(cancellationToken), null, TimeSpan.Zero, TimeSpan.FromMinutes(1));
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
private async Task ProcessAsync(CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
_logger.LogInformation("Role Assessor background service is running at: {time}", DateTimeOffset.Now);
|
|
|
|
if (cancellationToken.IsCancellationRequested)
|
|
return;
|
|
|
|
await _activityLogReader.Scan(cancellationToken);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
_logger.LogInformation("Operation was canceled");
|
|
}
|
|
catch (System.Exception ex)
|
|
{
|
|
_logger.LogError(ex, "An error occurred while reading the logs");
|
|
throw;
|
|
}
|
|
}
|
|
|
|
public Task StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
_logger.LogInformation("Stopping the Role Assessor background service.");
|
|
|
|
_timer?.Change(Timeout.Infinite, 0);
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_timer?.Dispose();
|
|
}
|
|
} |