Files
parr_api/PARR.NextRun/NextRunIntervalService.cs

130 lines
6.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.BLL.Services.Interfaces;
using PARR.Common.Domain;
using PARR.Constants;
using PARR.NextRun.Services;
using PARR.NextRun.Settings;
namespace PARR.NextRun
{
/// <summary>
/// Расчет nextRun по интервалу
/// </summary>
internal class NextRunIntervalService : INextRunIntervalService
{
private readonly WorkerSettings workerSettings;
private readonly ILogger<NextRunIntervalService> logger;
private readonly IIntervalService intervalService;
private readonly IServiceProvider serviceProvider;
public NextRunIntervalService(
WorkerSettings workerSettings,
ILogger<NextRunIntervalService> logger,
IIntervalService intervalService,
IServiceProvider serviceProvider
)
{
this.workerSettings = workerSettings;
this.logger = logger;
this.intervalService = intervalService;
this.serviceProvider = serviceProvider;
}
public async Task StartAsync()
{
logger.LogInformation("Запуск сервиса рассчета времени следующего создания наряда (nextRun)");
await intervalService.IntervalInitAsync(async () =>
{
using (var scope = serviceProvider.CreateScope())
{
var nextRunUpdateService = scope.ServiceProvider.GetRequiredService<INextRunUpdateService>();
await nextRunUpdateService.UpdateNextRunForTemplatesAsync(
// фильтр, только просроченные шаблоны
query => query.Where(t => t.NextRun < DateTimeOffset.UtcNow),
() => new HistoryInitiator
{
InitiatorComment = "Обновлён NextRun (интервал)",
InitiatorParrComponentId = ParrComponentsEnum.NextRun
},
"Интервал"
);
//var templateService = scope.ServiceProvider.GetRequiredService<ITemplateService>();
//var nextRunService = scope.ServiceProvider.GetRequiredService<INextRunService>();
//var robotConfigurationService = scope.ServiceProvider.GetRequiredService<IRobotConfigurationService>();
//await HandlerAsync(templateService, nextRunService, robotConfigurationService);
}
}, workerSettings.RepeatEvery);
}
///// <summary>
///// Рассчет следующей даты срабатываения
///// </summary>
///// <returns></returns>
//private async Task HandlerAsync(ITemplateService templateService, INextRunService nextRunService, IRobotConfigurationService robotConfigurationService)
//{
// logger.LogInformation("Начинаю обновлять NextRun по расписанию");
// await UpdateNextRunAsync(templateService, nextRunService, robotConfigurationService);
// logger.LogInformation($"Завершено обновление полей NextRun.");
//}
//private async Task UpdateNextRunAsync(ITemplateService templateService, INextRunService nextRunService, IRobotConfigurationService robotConfigurationService)
//{
// // выбираем все шаблоны с просроченным nextRun в статусе Used
// var templatesForUpdate = await templateService.Get()
// .Include(t => t.RobotConfigurations)
// .Where(t =>
// t.StatusTypeId == TemplateStatusTypeEnum.Used
// && t.NextRun < DateTimeOffset.UtcNow
// ).ToListAsync();
// logger.LogInformation("Найдено шаблонов в статусе Used с просроченным NextRun {count} шт.", templatesForUpdate.Count);
// if (!templatesForUpdate.Any())
// return;
// foreach (var template in templatesForUpdate)
// {
// var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
// if (newNextRun.HasValue)
// {
// template.LastRun = template.NextRun;
// template.NextRun = newNextRun.Value;
// //так как nextRun обновился, пробуем поставить задание на обновление
// var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.ScheduleOrder, template);
// robotConfigurationService.SetUpdateTaskStatusIfAllow(config);
// }
// else
// {
// logger.LogError("При расчете nextRun для шаблона {templateId}, '{templateName}', nextRun=null. Это значит что при расчете возникла ошибка.", template.Id, template.Name);
// }
// }
// if (await templateService.CommitAsync(new HistoryInitiator { InitiatorComment = "Обновлён NextRun", InitiatorParrComponentId = ParrComponentsEnum.NextRun }))
// {
// logger.LogInformation("Обновлены значения полей NextRun для шаблонов в статусе Used, {count} шт.", templatesForUpdate.Count);
// }
// else
// {
// logger.LogError("Ошибка при обновлении значений полей NextRun, для шаблонов в статусе Used, {count} шт.", templatesForUpdate.Count);
// }
//}
}
}