Church.Net.API/WebAPI/Services/WorkerService.cs
2022-10-02 09:50:42 -07:00

76 lines
2.3 KiB
C#

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<string> 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<IEnumerable<IScheduledTask>>();
var loggingService = scope.ServiceProvider.GetRequiredService<ILoggingService>();
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";
}
}
}