- Add WorkerSettings class and update appsettings for config-driven setup - Integrate Quartz.NET for job scheduling (FinalizeDocumentJob, APIEnvelopeJob) - Refactor Program.cs for DI of services (TempFileManager, PDFBurner, etc.) - Implement TempFileManager for temp folder management and cleanup - Rewrite Worker class for config validation, DB check, and lifecycle logging - Update csproj to include Quartz and EnvelopeGenerator.Jobs references - Improve maintainability, error handling, and logging throughout
72 lines
2.4 KiB
C#
72 lines
2.4 KiB
C#
using EnvelopeGenerator.WorkerService.Configuration;
|
|
using EnvelopeGenerator.WorkerService.Services;
|
|
using Microsoft.Data.SqlClient;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace EnvelopeGenerator.WorkerService;
|
|
|
|
public class Worker : BackgroundService
|
|
{
|
|
private readonly ILogger<Worker> _logger;
|
|
private readonly WorkerSettings _settings;
|
|
private readonly TempFileManager _tempFiles;
|
|
|
|
public Worker(
|
|
ILogger<Worker> logger,
|
|
IOptions<WorkerSettings> settings,
|
|
TempFileManager tempFiles)
|
|
{
|
|
_logger = logger;
|
|
_settings = settings.Value;
|
|
_tempFiles = tempFiles;
|
|
}
|
|
|
|
public override async Task StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
_logger.LogInformation("Starting EnvelopeGenerator worker...");
|
|
_logger.LogInformation("Debug mode: {Debug}", _settings.Debug);
|
|
|
|
ValidateConfiguration();
|
|
await EnsureDatabaseConnectionAsync(cancellationToken);
|
|
await _tempFiles.CreateAsync(cancellationToken);
|
|
|
|
await base.StartAsync(cancellationToken);
|
|
}
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
_logger.LogInformation("EnvelopeGenerator worker is running. Jobs are scheduled every {Interval} minute(s).", Math.Max(1, _settings.IntervalMinutes));
|
|
await Task.Delay(Timeout.Infinite, stoppingToken);
|
|
}
|
|
|
|
public override async Task StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
_logger.LogInformation("Stopping EnvelopeGenerator worker...");
|
|
await _tempFiles.CleanupAsync(cancellationToken);
|
|
await base.StopAsync(cancellationToken);
|
|
}
|
|
|
|
private void ValidateConfiguration()
|
|
{
|
|
if (string.IsNullOrWhiteSpace(_settings.ConnectionString))
|
|
{
|
|
throw new InvalidOperationException("Connection string cannot be empty. Configure 'WorkerSettings:ConnectionString'.");
|
|
}
|
|
}
|
|
|
|
private async Task EnsureDatabaseConnectionAsync(CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
await using var connection = new SqlConnection(_settings.ConnectionString);
|
|
await connection.OpenAsync(cancellationToken);
|
|
_logger.LogInformation("Database connection established successfully.");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Database connection could not be established.");
|
|
throw;
|
|
}
|
|
}
|
|
}
|