using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using MTG_CollectionVerwaltung.API_Connector; using MTG_CollectionVerwaltung.Data.MTGCollection; using System; using System.IO; using System.Threading; using System.Threading.Tasks; public class ScryfallDBUpdater : BackgroundService { private readonly ILogger _logger; private readonly IServiceProvider _serviceProvider; private readonly TimeSpan interval = TimeSpan.FromDays(7); private const string actFile = "nextActualisation.txt"; private const string dwlFile = "nextDownload.txt"; public ScryfallDBUpdater(ILogger logger, IServiceProvider serviceProvider) { _logger = logger; _serviceProvider = serviceProvider; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { DateTime nextUpdate = DateTime.MinValue; if (File.Exists(actFile) && DateTime.TryParse(File.ReadAllText(actFile), out var fileTime)) { nextUpdate = fileTime; } var delay = TimeSpan.FromDays(7) - (DateTime.Now-nextUpdate); if (delay < TimeSpan.Zero) delay = TimeSpan.Zero; bool dwupdate = true; await Task.Delay(delay, stoppingToken); while (!stoppingToken.IsCancellationRequested) { try { using var scope = _serviceProvider.CreateScope(); var dbContext = scope.ServiceProvider.GetRequiredService(); var connector = new ScryfallConnector(dbContext); _logger.LogInformation("Scryfall DB Update startet..."); if (File.Exists(dwlFile) && DateTime.TryParse(File.ReadAllText(dwlFile), out var dwTime)) { dwupdate = dwTime.Day != DateTime.Now.Day; } if(dwupdate) await connector.LoadDataAsync(); File.WriteAllText(dwlFile, DateTime.Now.ToString()); await connector.ActualizeDbAsync(); File.WriteAllText(actFile, DateTime.Now.ToString()); _logger.LogInformation("Scryfall DB Update abgeschlossen."); dbContext.ChangeTracker.Clear(); } catch (Exception ex) { _logger.LogError(ex, "Fehler beim Scryfall DB Update"); } await Task.Delay(interval, stoppingToken); } } }