feat(dal, esppSync, nextRun): При синхронизации расписаний и шаблонов, при расчете nextRun в NextRunWorker - установить задание на обновление объекта, можно только если объект в статусе Ок. NextRunWorker - рефакторинг.

This commit is contained in:
Mikhail Trubnikov
2026-03-11 12:10:11 +10:00
parent 8cfccd7671
commit b9d1f923b3
10 changed files with 359 additions and 175 deletions

View File

@@ -1,12 +1,9 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.BLL.Services.Interfaces;
using PARR.Common.Domain;
using PARR.Constants;
using PARR.DAL.NextRunServices;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.Services.Interfaces.Job;
using PARR.NextRun.Services;
using PARR.NextRun.Settings;
namespace PARR.NextRun
@@ -42,76 +39,89 @@ namespace PARR.NextRun
{
using (var scope = serviceProvider.CreateScope())
{
//var appInWorkService = scope.ServiceProvider.GetService<IApplicationsInWorkService>();
//var esppSchService = scope.ServiceProvider.GetService<IEsppScheduleTransformService>();
var templateService = scope.ServiceProvider.GetService<ITemplateService>();
var jobGroupService = scope.ServiceProvider.GetService<IJobGroupService>();
var nextRunService = scope.ServiceProvider.GetService<INextRunService>();
var nextRunUpdateService = scope.ServiceProvider.GetRequiredService<INextRunUpdateService>();
if (templateService == null || nextRunService == null || jobGroupService == null)
throw new Exception($"Не смог получить серивс {nameof(ITemplateService)} или {nameof(INextRunService)} или {nameof(IJobGroupService)}");
await nextRunUpdateService.UpdateNextRunForTemplatesAsync(
// фильтр, только просроченные шаблоны
query => query.Where(t => t.NextRun < DateTimeOffset.UtcNow),
() => new HistoryInitiator
{
InitiatorComment = "Обновлён NextRun (интервал)",
InitiatorParrComponentId = ParrComponentsEnum.NextRun
},
"Интервал"
);
await HandlerAsync(templateService, nextRunService, jobGroupService);
//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, IJobGroupService jobGroupService)
{
logger.LogInformation("Начинаю обновлять NextRun по расписанию");
///// <summary>
///// Рассчет следующей даты срабатываения
///// </summary>
///// <returns></returns>
//private async Task HandlerAsync(ITemplateService templateService, INextRunService nextRunService, IRobotConfigurationService robotConfigurationService)
//{
// logger.LogInformation("Начинаю обновлять NextRun по расписанию");
await UpdateNextRunAsync(templateService, nextRunService, jobGroupService);
// await UpdateNextRunAsync(templateService, nextRunService, robotConfigurationService);
logger.LogInformation($"Завершено обновление полей NextRun.");
}
// logger.LogInformation($"Завершено обновление полей NextRun.");
//}
private async Task UpdateNextRunAsync(ITemplateService templateService, INextRunService nextRunService, IJobGroupService jobGroupService)
{
// выбираем все шаблоны с просроченным nextRun в статусе Used
//private async Task UpdateNextRunAsync(ITemplateService templateService, INextRunService nextRunService, IRobotConfigurationService robotConfigurationService)
//{
// // выбираем все шаблоны с просроченным nextRun в статусе Used
var templatesForUpdate = await templateService.Get()
.Where(t =>
t.StatusTypeId == TemplateStatusTypeEnum.Used
&& t.NextRun < DateTimeOffset.UtcNow
).ToListAsync();
// 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);
// logger.LogInformation("Найдено шаблонов в статусе Used с просроченным NextRun {count} шт.", templatesForUpdate.Count);
if (!templatesForUpdate.Any())
return;
// if (!templatesForUpdate.Any())
// return;
foreach (var template in templatesForUpdate)
{
var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
// foreach (var template in templatesForUpdate)
// {
// var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
if (newNextRun.HasValue)
{
template.LastRun = template.NextRun;
template.NextRun = newNextRun.Value;
}
else
{
logger.LogError("При расчете nextRun для шаблона {templateId}, '{templateName}', nextRun=null. Это значит что при расчете возникла ошибка.", template.Id, template.Name);
}
}
// if (newNextRun.HasValue)
// {
// template.LastRun = template.NextRun;
// template.NextRun = newNextRun.Value;
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);
}
// //так как 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);
// }
//}