using ServerManager.SyncMethods; using System.Net.Http.Headers; namespace ServerManager { public class Worker : BackgroundService { private readonly ILogger _logger; private readonly IServiceProvider _serviceProvider; private readonly IConfiguration m_configuration; private HttpClient m_httpClient; public Worker(ILogger logger, IServiceProvider serviceProvider, IConfiguration configuration) { _logger = logger; _serviceProvider = serviceProvider; m_configuration = configuration; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { string baseurl = m_configuration.GetValue("BaseUrl", "")!; HttpClient httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(baseurl); string token = m_configuration.GetValue("APIKEY", "")!; httpClient.DefaultRequestHeaders.Add("BISK-API-KEY", token); using var scope = _serviceProvider.CreateScope(); var salesSync = scope.ServiceProvider.GetRequiredService(); var productSync = scope.ServiceProvider.GetRequiredService(); var companySync = scope.ServiceProvider.GetRequiredService(); while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Worker running at: {time} ", DateTimeOffset.Now); List runTask = new List(); runTask.AddRange(salesSync.GetSalesSyncTask(httpClient)); runTask.AddRange(productSync.GetProductSyncTask(httpClient)); runTask.AddRange(companySync.GetCompanySyncTask(httpClient)); // Wait for all tasks to complete await Task.WhenAll(runTask); await Task.Delay(1000, stoppingToken); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } } }