This commit is contained in:
Mikhail Kuznetsov
2026-01-23 11:29:49 +10:00
4 changed files with 80 additions and 59 deletions

View File

@@ -20,20 +20,20 @@ namespace PARR.BLL.Services.Implementations
{
nextStart = DateTimeOffset.UtcNow;
logger.LogInformation($"Запуск по расписанию. Интервал: {interval}, дата: {nextStart}");
logger.LogInformation("Запуск по расписанию. Интервал: {interval}, дата: {nextStart}", interval, nextStart);
await intervalHandler.Invoke();
nextStart = nextStart.Add(interval);
logger.LogInformation($"Следующая дата запуска: {nextStart}. Интервал: {interval}.");
logger.LogInformation("Следующая дата запуска: {nextStart}. Интервал: {interval}.", nextStart, interval);
var intervalOffset = nextStart - DateTimeOffset.UtcNow;
if (intervalOffset < TimeSpan.Zero)
{
intervalOffset = TimeSpan.Zero;
logger.LogWarning($"Время следующего запуска изменено на сейчас. Так как рассчитанное время запуска меньше чем сейчас, {nextStart}<{DateTimeOffset.UtcNow}. " +
$"Это произошло потому что время выполнения основного метода больше чем заданный интервал повторений.");
logger.LogWarning("Время следующего запуска изменено на сейчас. Так как рассчитанное время запуска меньше чем сейчас, {nextStart}<{now}. " +
$"Это произошло потому что время выполнения основного метода больше чем заданный интервал повторений.", nextStart, DateTimeOffset.UtcNow);
}
await Task.Delay(intervalOffset);

View File

@@ -5,19 +5,19 @@ namespace PARR.DAL.NextRunServices
public interface INextRunService
{
/// <summary>
/// Получить список TemplateId, NextRun по jobGroupId с автораспределением
/// Получить список TemplateId, NextRun по jobGroupId с автораспределением (распределить шаблоны в группе работ)
/// </summary>
/// <param name="jobGroupId"></param>
/// <returns></returns>
Task<List<TemplateNextRunResultDto>?> GetNextRunForJobGroupWithAutoDistributionAsync(Guid jobGroupId);
///// <summary>
///// Получить NextRun по jobGroupId с расписанием ЕСПП
///// </summary>
///// <param name="jobGroupId"></param>
///// <returns></returns>
//Task<DateTimeOffset> GetNextRunForJobGroupWithEsppSchedulleAsync(Guid jobGroupId);
/// <summary>
/// Получить NextRun по jobGroupId с расписанием ЕСПП
/// </summary>
/// <param name="jobGroupId"></param>
/// <returns></returns>
Task<DateTimeOffset> GetNextRunForJobGroupWithEsppSchedulleAsync(Guid jobGroupId);
/// <summary>

View File

@@ -126,19 +126,19 @@ namespace PARR.DAL.NextRunServices
}
//public async Task<DateTimeOffset> GetNextRunForJobGroupWithEsppSchedulleAsync(Guid jobGroupId)
//{
// var jobGroup = await jobGroupService.Get().AsNoTracking().FirstOrDefaultAsync(t => t.Id == jobGroupId);
public async Task<DateTimeOffset> GetNextRunForJobGroupWithEsppSchedulleAsync(Guid jobGroupId)
{
var jobGroup = await jobGroupService.Get().AsNoTracking().FirstOrDefaultAsync(t => t.Id == jobGroupId);
// if (jobGroup == null)
// {
// logger.LogError("Не найдена группа работ с Id: {jobGroupId}.", jobGroupId);
// throw new ArgumentNullException(nameof(jobGroupId), $"Не найдена группа работ с Id: {jobGroupId}");
// }
if (jobGroup == null)
{
logger.LogError("Не найдена группа работ с Id: {jobGroupId}.", jobGroupId);
throw new ArgumentNullException(nameof(jobGroupId), $"Не найдена группа работ с Id: {jobGroupId}");
}
// // Берем из обычного расписания ЕСПП
// return await esppScheduleTransformService.GetNextDateAsync(jobGroupId, jobGroup.ReferenceDate);
//}
// Берем из обычного расписания ЕСПП
return await esppScheduleTransformService.GetNextDateAsync(jobGroupId, jobGroup.ReferenceDate);
}
public async Task<DateTimeOffset> GetNextRunForNewTemplateAsync(Guid jobGroupId)

View File

@@ -60,11 +60,28 @@ namespace PARR.NextRun
/// <returns></returns>
private async Task HandlerAsync(ITemplateService templateService, INextRunService nextRunService, IJobGroupService jobGroupService)
{
#region логика для групп у которых не включено автораспределение
logger.LogInformation("Начинаю обновлять NextRun по расписанию");
// обновляем для групп у которых не включено автораспределение
await UpdateNextRunWithEsppScheduleAsync(templateService, nextRunService, jobGroupService);
// для групп у которых включено автораспределение
await UpdateNextRunWithAutodistributeScheduleAsync(templateService, nextRunService, jobGroupService);
logger.LogInformation($"Завершено обновление полей NextRun.");
}
/// <summary>
/// Обновить nextRun для ВСЕХ шаблонов, для групп у которых расписание ЕСПП (выключено автораспределение)
/// </summary>
/// <returns></returns>
private async Task UpdateNextRunWithEsppScheduleAsync(ITemplateService templateService, INextRunService nextRunService, IJobGroupService jobGroupService)
{
// выбираем шаблоны которые не учавствуют в автораспределении
// и у которых IsUnuser==false
// и у которых Used
// затем группируем по GroupId, так как nextRun и расписание настраивается для группы, то для всех дочерних шаблонов, nextRun будет одинаковым
// обновляем для всех шаблонов, у которых nextRun!=рассчитанному
var groups = await jobGroupService.Get()
@@ -72,13 +89,13 @@ namespace PARR.NextRun
.Select(t => new { t.Id, t.ReferenceDate })
.ToListAsync();
logger.LogInformation("Найдено {GroupCount} групп для обработки.", groups.Count);
logger.LogInformation("Найдено {GroupCount} групп с выключенным автораспределением для обработки.", groups.Count);
foreach (var group in groups)
{
//получаем по каждой группе следующий nextRun и сравниваем с существующим, если не равны, то обновляем
//var nextRun = await esppScheduleTransformService.GetNextDateAsync(group.Id, group.ReferenceDate);
var nextRun = await nextRunService.GetNextRunForTemplateAsync(group.Id, false);
var nextRun = await nextRunService.GetNextRunForJobGroupWithEsppSchedulleAsync(group.Id);
// Загружаем только шаблоны текущей группы где nextRun в БД не равен расчетному
@@ -86,6 +103,8 @@ namespace PARR.NextRun
.Where(t => t.StatusTypeId == TemplateStatusTypeEnum.Used && t.Job!.GroupId == group.Id && t.NextRun != nextRun)
.ToListAsync();
logger.LogInformation("Для группы {groupId}, шаблонов для обновления где nextRun!=рассчетному {newNextRun} найдено {count} шт.", group.Id, nextRun, templatesToUpdate.Count);
if (!templatesToUpdate.Any())
continue;
@@ -97,52 +116,54 @@ namespace PARR.NextRun
}
// Коммитим изменения для этой группы
if (await templateService.CommitAsync(new HistoryInitiator { InitiatorComment = "Обновлён NextRun", InitiatorParrComponentId = Constants.ParrComponentsEnum.NextRun }))
logger.LogInformation($"Обновлены значения полей NextRun для шаблонов группы: {group.Id}, " +
if (await templateService.CommitAsync(new HistoryInitiator { InitiatorComment = "Обновлён NextRun", InitiatorParrComponentId = ParrComponentsEnum.NextRun }))
logger.LogInformation($"Обновлены значения полей NextRun для шаблонов группы: {group.Id} с выключенным автораспределением, " +
$"refDate: {group.ReferenceDate}. Обновлен nextRun: {nextRun} для шаблонов {templatesToUpdate.Count} шт.");
else
{
logger.LogError($"Ошибка при обновлении значений полей NextRun: {nextRun}, для шаблонов {templatesToUpdate.Count} шт., группы {group.Id}, refDate: {group.ReferenceDate} ");
logger.LogError($"Ошибка при обновлении значений полей NextRun: {nextRun}, для шаблонов {templatesToUpdate.Count} шт., группы {group.Id} с выключенным автораспределением, refDate: {group.ReferenceDate} ");
}
}
#endregion
//todo: когда будет автораспределение, для него придумать логику как считать
//TODO:!!! Написать логику для групп у которых включено автораспределение!!!
}
#region old logic
//var templates = await templateService.Get()
// .Include(t => t.Job)
// .ThenInclude(t => t.Group)
// .Where(t => t.NextRun < DateTimeOffset.UtcNow).ToListAsync();
/// <summary>
/// Обновить ПРОСРОЧЕННЫЕ NextRun для групп у которых включено автораспределение
/// </summary>
/// <param name="templateService"></param>
/// <param name="nextRunService"></param>
/// <param name="jobGroupService"></param>
/// <returns></returns>
private async Task UpdateNextRunWithAutodistributeScheduleAsync(ITemplateService templateService, INextRunService nextRunService, IJobGroupService jobGroupService)
{
// получаем список всех шаблонов с включенным автораспределением у которых ПРОСРОЧЕН nextRun и они Used
// обновляем у них NextRun
//logger.LogDebug($"Шаблонов для обновления: {templates.Count()} шт.");
var templatesForUpdate = await templateService.Get()
.Where(t => t.StatusTypeId == TemplateStatusTypeEnum.Used && t.Job.Group.IsAutoDistributionEnabled == true && t.NextRun < DateTimeOffset.UtcNow)
.ToListAsync();
//int errorsCount = 0;
logger.LogInformation("Найдено шаблонов с автораспределением, с просроченным NextRun {count} шт.", templatesForUpdate.Count);
//foreach (var template in templates)
//{
// var nextRun = await esppScheduleTransformService.GetNextDateAsync(template.Job!.GroupId, template.NextRun);
// template.LastRun = template.NextRun;
// template.NextRun = nextRun;
if (!templatesForUpdate.Any())
return;
// if (await templateService.CommitAsync(new HistoryInitiator { InitiatorComment = "Обновлён NextRun", InitiatorParrComponentId = Constants.ParrComponentsEnum.NextRun }))
// logger.LogDebug($"Обновлены значения полей NextRun: {template.NextRun}, LastRun: {template.LastRun} для шаблона {template.Name}, {template.Id}");
// else
// {
// logger.LogError($"Ошибка при обновлении значений полей NextRun: {template.NextRun}, LastRun: {template.LastRun} для шаблона {template.Name}, {template.Id}");
// errorsCount++;
// }
//}
foreach (var template in templatesForUpdate)
{
var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
//logger.LogInformation($"Завершено обновление полей NextRun. Полей в задании: {templates.Count()}, обновлено: {templates.Count() - errorsCount}, ошибок: {errorsCount}");
template.LastRun = template.NextRun;
template.NextRun = newNextRun;
}
#endregion
logger.LogInformation($"Завершено обновление полей NextRun.");
if (await templateService.CommitAsync(new HistoryInitiator { InitiatorComment = "Обновлён NextRun", InitiatorParrComponentId = ParrComponentsEnum.NextRun }))
{
logger.LogInformation("Обновлены значения ПРОСРОЧЕННЫХ полей NextRun для шаблонов с ВКЛЮЧЕННЫМ автораспределением, {count} шт.", templatesForUpdate.Count);
}
else
{
logger.LogError("Ошибка при обновлении ПРОСРОЧЕННЫХ значений полей NextRun, для шаблонов {count} шт., с ВКЛЮЧЕННЫМ автораспределением", templatesForUpdate.Count);
}
}
}
}