73 lines
2.5 KiB
C#
73 lines
2.5 KiB
C#
using System;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Inventory.Core;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Inventory.Agent
|
|
{
|
|
public class Worker : BackgroundService
|
|
{
|
|
private readonly ILogger<Worker> _logger;
|
|
private readonly IServiceProvider _serviceProvider;
|
|
private readonly IHostApplicationLifetime _hostApplicationLifetime;
|
|
|
|
public Worker(ILogger<Worker> logger, IServiceProvider serviceProvider, IHostApplicationLifetime hostApplicationLifetime)
|
|
{
|
|
_logger = logger;
|
|
_serviceProvider = serviceProvider;
|
|
_hostApplicationLifetime = hostApplicationLifetime;
|
|
}
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
_logger.LogInformation("Inventory Agent service starting.");
|
|
|
|
// Start with a basic test of service functionality
|
|
try
|
|
{
|
|
_logger.LogInformation("Testing service startup...");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error during service startup test");
|
|
return;
|
|
}
|
|
|
|
_logger.LogInformation("Inventory Agent starting.");
|
|
|
|
// Perform an initial run on startup
|
|
await DoWork(stoppingToken);
|
|
|
|
var updateIntervalMinutes = Core.Secrets.UpdateIntervalMinutes;
|
|
_logger.LogInformation("Update interval set to {Minutes} minutes.", updateIntervalMinutes);
|
|
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(updateIntervalMinutes));
|
|
|
|
while (await timer.WaitForNextTickAsync(stoppingToken))
|
|
{
|
|
await DoWork(stoppingToken);
|
|
}
|
|
}
|
|
|
|
private async Task DoWork(CancellationToken stoppingToken)
|
|
{
|
|
_logger.LogInformation("Starting inventory update workflow.");
|
|
try
|
|
{
|
|
using var scope = _serviceProvider.CreateScope();
|
|
var updateWorkflow = scope.ServiceProvider.GetRequiredService<UpdateWorkflow>();
|
|
await updateWorkflow.Run();
|
|
_logger.LogInformation("Inventory update completed successfully.");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "An error occurred during the inventory update.");
|
|
}
|
|
}
|
|
}
|
|
} |