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

View File

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

View File

@@ -126,19 +126,19 @@ namespace PARR.DAL.NextRunServices
} }
//public async Task<DateTimeOffset> GetNextRunForJobGroupWithEsppSchedulleAsync(Guid jobGroupId) public async Task<DateTimeOffset> GetNextRunForJobGroupWithEsppSchedulleAsync(Guid jobGroupId)
//{ {
// var jobGroup = await jobGroupService.Get().AsNoTracking().FirstOrDefaultAsync(t => t.Id == jobGroupId); var jobGroup = await jobGroupService.Get().AsNoTracking().FirstOrDefaultAsync(t => t.Id == jobGroupId);
// if (jobGroup == null) if (jobGroup == null)
// { {
// logger.LogError("Не найдена группа работ с Id: {jobGroupId}.", jobGroupId); logger.LogError("Не найдена группа работ с Id: {jobGroupId}.", jobGroupId);
// throw new ArgumentNullException(nameof(jobGroupId), $"Не найдена группа работ с Id: {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) public async Task<DateTimeOffset> GetNextRunForNewTemplateAsync(Guid jobGroupId)

View File

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