using System; using AAIntegration.SimmonsBank.API.Configs; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using AAIntegration.SimmonsBank.API.Processes; using AAIntegration.SimmonsBank.API.Services; namespace AAIntegration.SimmonsBank.API.Workers; public class EnvelopeFundWorker : BackgroundService { private readonly EnvelopeFundConfig _config; private readonly IEnvelopeFundingProcess _envelopeFundingProcess; private readonly ILogger _logger; private readonly IServiceScopeFactory _serviceScopeFactory; public EnvelopeFundWorker(IOptions config, IEnvelopeFundingProcess envelopeFundingProcess, ILogger logger, IServiceScopeFactory serviceScopeFactory) { _config = config.Value; _envelopeFundingProcess = envelopeFundingProcess; _logger = logger; _serviceScopeFactory = serviceScopeFactory; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { DateTime? lastExecutedOn = null; using (var scope = _serviceScopeFactory.CreateScope()) { IEnvelopeService envelopeService = scope.ServiceProvider.GetService(); // This is how we keep the app running (in the background) while (!stoppingToken.IsCancellationRequested) { if (lastExecutedOn != null) { int minutesRemaining = _config.CheckIntervalInMinutes - (int)DateTime.UtcNow.Subtract(lastExecutedOn.Value).TotalMinutes; await Task.Delay(TimeSpan.FromMinutes(minutesRemaining < 0 ? 0 : minutesRemaining), stoppingToken); } lastExecutedOn = DateTime.UtcNow; _logger.LogInformation("EnvelopeFundWorker running at: {time}", DateTimeOffset.Now); await _envelopeFundingProcess.FundEnvelopes(envelopeService); } } } }