2022-12-05 10:53:24 +05:00
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
2022-12-02 14:45:20 +05:00
|
|
|
|
using Microsoft.Extensions.Hosting;
|
|
|
|
|
using System;
|
|
|
|
|
using System.Threading;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
2023-10-08 21:20:28 +05:00
|
|
|
|
namespace AsbCloudInfrastructure.Background;
|
2022-12-02 14:45:20 +05:00
|
|
|
|
|
2023-10-08 21:20:28 +05:00
|
|
|
|
/// <summary>
|
|
|
|
|
/// Сервис для фонового выполнения работы
|
|
|
|
|
/// </summary>
|
|
|
|
|
public class BackgroundWorker : BackgroundService
|
|
|
|
|
{
|
|
|
|
|
private static readonly TimeSpan executePeriod = TimeSpan.FromSeconds(10);
|
|
|
|
|
private static readonly TimeSpan minDelay = TimeSpan.FromSeconds(2);
|
|
|
|
|
private readonly IServiceProvider serviceProvider;
|
2022-12-02 14:45:20 +05:00
|
|
|
|
|
2023-10-08 21:20:28 +05:00
|
|
|
|
public WorkStore WorkStore { get; } = new WorkStore();
|
|
|
|
|
public Work? CurrentWork;
|
2022-12-02 14:45:20 +05:00
|
|
|
|
|
2023-10-08 21:20:28 +05:00
|
|
|
|
public BackgroundWorker(IServiceProvider serviceProvider)
|
|
|
|
|
{
|
|
|
|
|
this.serviceProvider = serviceProvider;
|
|
|
|
|
}
|
2022-12-02 14:45:20 +05:00
|
|
|
|
|
2023-10-08 21:20:28 +05:00
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken token)
|
|
|
|
|
{
|
|
|
|
|
while (!token.IsCancellationRequested)
|
2022-12-02 14:45:20 +05:00
|
|
|
|
{
|
2023-10-08 21:20:28 +05:00
|
|
|
|
var work = WorkStore.GetNext();
|
|
|
|
|
if (work is null)
|
2022-12-02 14:45:20 +05:00
|
|
|
|
{
|
2023-10-08 21:20:28 +05:00
|
|
|
|
await Task.Delay(executePeriod, token);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
2023-10-08 13:09:09 +05:00
|
|
|
|
|
2023-10-08 21:20:28 +05:00
|
|
|
|
CurrentWork = work;
|
|
|
|
|
using var scope = serviceProvider.CreateScope();
|
2022-12-02 14:45:20 +05:00
|
|
|
|
|
2023-10-08 21:20:28 +05:00
|
|
|
|
var result = await work.Start(scope.ServiceProvider, token);
|
2023-10-08 13:09:09 +05:00
|
|
|
|
|
2023-10-08 21:20:28 +05:00
|
|
|
|
if (!result)
|
2023-10-09 13:12:45 +05:00
|
|
|
|
WorkStore.Felled.Add(work);
|
2023-10-08 21:20:28 +05:00
|
|
|
|
|
|
|
|
|
CurrentWork = null;
|
|
|
|
|
await Task.Delay(minDelay, token);
|
2022-12-02 14:45:20 +05:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|