DD.WellWorkover.Cloud/AsbCloudWebApi/Controllers/PeriodicBackgroundWorkerController.cs

70 lines
2.0 KiB
C#
Raw Normal View History

using AsbCloudApp.Data;
2023-11-03 17:02:44 +05:00
using AsbCloudInfrastructure.Background;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
2023-11-03 17:02:44 +05:00
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
2024-08-19 10:01:07 +05:00
namespace AsbCloudWebApi.Controllers;
[Route("api/[controller]")]
[Authorize]
[ApiController]
public class PeriodicBackgroundWorkerController : ControllerBase
2023-11-03 17:02:44 +05:00
{
2024-08-19 10:01:07 +05:00
private readonly PeriodicBackgroundWorker worker;
private readonly IServiceProvider serviceProvider;
2023-11-03 17:02:44 +05:00
2024-08-19 10:01:07 +05:00
public PeriodicBackgroundWorkerController(
PeriodicBackgroundWorker worker,
IServiceProvider serviceProvider)
{
this.worker = worker;
this.serviceProvider = serviceProvider;
}
2023-11-03 17:02:44 +05:00
2024-08-19 10:01:07 +05:00
[HttpGet]
public IActionResult GetAll()
{
var result = new
2023-11-03 17:02:44 +05:00
{
2024-08-19 10:01:07 +05:00
currentWork = (BackgroundWorkDto?)worker.CurrentWork,
worker.MainLoopLastException,
works = worker.Works.Select(work => (BackgroundWorkDto)work.Work),
};
return Ok(result);
}
2023-11-03 17:02:44 +05:00
2024-08-19 10:01:07 +05:00
/// <summary>
/// Запуск задачи по Id
/// </summary>
/// <param name="workId">Id задачи</param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet("start/{workId}")]
public async Task<IActionResult> Start(string workId, CancellationToken token)
{
var targetWork = worker.Works.FirstOrDefault(w => w.Work.Id == workId);
if(targetWork is not null)
{
2024-08-19 10:01:07 +05:00
using (var scope = serviceProvider.CreateScope()) {
2024-08-19 10:01:07 +05:00
var result = await targetWork.Work.Start(scope.ServiceProvider, token);
return Ok(result);
}
}
2024-08-19 10:01:07 +05:00
return BadRequest("Work not found by workId");
}
2024-08-19 10:01:07 +05:00
[HttpPost("restart"), Obsolete("temporary method")]
public async Task<IActionResult> RestartAsync(CancellationToken token)
{
await worker.StopAsync(token);
await worker.StartAsync(token);
return Ok();
2023-11-03 17:02:44 +05:00
}
}