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; namespace WebAPI.Services { public class WorkerService : BackgroundService { private IEnumerable scheduledTasks; private ILoggingService loggingService; private readonly IWebHostEnvironment env; private static bool initialized = false; public WorkerService( IEnumerable scheduledTasks, ILoggingService loggingService ) { this.scheduledTasks = scheduledTasks; this.loggingService = loggingService; } 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(); 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"; } } }