DD.WellWorkover.Cloud/AsbCloudInfrastructure/Background/BackgroundWorker.cs

50 lines
1.4 KiB
C#
Raw Normal View History

2022-12-05 10:53:24 +05:00
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;
2023-10-08 21:20:28 +05:00
namespace AsbCloudInfrastructure.Background;
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;
2023-10-08 21:20:28 +05:00
public WorkStore WorkStore { get; } = new WorkStore();
public Work? CurrentWork;
2023-10-08 21:20:28 +05:00
public BackgroundWorker(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
2023-10-08 21:20:28 +05:00
protected override async Task ExecuteAsync(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
2023-10-08 21:20:28 +05:00
var work = WorkStore.GetNext();
if (work is null)
{
2023-10-08 21:20:28 +05:00
await Task.Delay(executePeriod, token);
continue;
}
2023-10-08 21:20:28 +05:00
CurrentWork = work;
using var scope = serviceProvider.CreateScope();
2023-10-08 21:20:28 +05:00
var result = await work.Start(scope.ServiceProvider, token);
2023-10-08 21:20:28 +05:00
if (!result)
WorkStore.Felled.Add(work);
2023-10-08 21:20:28 +05:00
CurrentWork = null;
await Task.Delay(minDelay, token);
}
}
}