using Microsoft.Extensions.Hosting; using System.Threading.Tasks; using System.Threading; using System; using WebAPI.Services.Interfaces; using System.Collections.Generic; using System.Linq; using Church.Net.Utility; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; namespace WebAPI.Services { public class WorkerService : BackgroundService { private readonly IServiceProvider serviceProvider; private readonly IWebHostEnvironment env; private static bool initialized = false; public WorkerService( IServiceProvider serviceProvider ) { this.serviceProvider = serviceProvider; } private const int generalDelay = 5 * 60 * 1000; // 10 seconds protected override async Task ExecuteAsync(CancellationToken stoppingToken) { //await DoBackupAsync(); while (!stoppingToken.IsCancellationRequested) { await Task.Delay(generalDelay, stoppingToken); await DoBackupAsync(); } } private async Task DoBackupAsync() { // here i can write logic for taking backup at midnight //if (IsMidnight()) //{ // Console.WriteLine("Executing background task"); // TakeBackup(); //} var now = DateTimeHelper.Now(); using (var scope = serviceProvider.CreateScope()) { var scheduledTasks = scope.ServiceProvider.GetRequiredService>(); var loggingService = scope.ServiceProvider.GetRequiredService(); foreach (var worker in scheduledTasks) { try { if (worker.CheckTime(now)) { loggingService.Log($"Running {worker.Description}"); await worker.RunTask(); } } catch (Exception ex) { loggingService.Error(ex, worker.Description); } } } return "Done"; } } }