61 lines
2.2 KiB
C#
61 lines
2.2 KiB
C#
using System;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
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 IConfiguration _configuration;
|
|
private readonly IServiceProvider _serviceProvider;
|
|
|
|
public Worker(ILogger<Worker> logger, IConfiguration configuration, IServiceProvider serviceProvider)
|
|
{
|
|
_logger = logger;
|
|
_configuration = configuration;
|
|
_serviceProvider = serviceProvider;
|
|
}
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
_logger.LogInformation("Inventory Agent starting.");
|
|
|
|
// Perform an initial run on startup
|
|
await DoWork(stoppingToken);
|
|
|
|
var updateIntervalMinutes = _configuration.GetValue<int>("UPDATE_INTERVAL_MINUTES");
|
|
if (updateIntervalMinutes <= 0)
|
|
{
|
|
updateIntervalMinutes = 60; // Default to 60 minutes if not configured or invalid
|
|
}
|
|
_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<Inventory.Core.UpdateWorkflow>();
|
|
await updateWorkflow.Run();
|
|
_logger.LogInformation("Inventory update completed successfully.");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "An error occurred during the inventory update.");
|
|
}
|
|
}
|
|
}
|
|
} |