| | | 1 | | using Hangfire; |
| | | 2 | | using Microsoft.EntityFrameworkCore; |
| | | 3 | | using OzonDomains.Models; |
| | | 4 | | using OzonRepositories.Context; |
| | | 5 | | using Services.HangfireService; |
| | | 6 | | |
| | | 7 | | namespace Services.OrderControlServices; |
| | | 8 | | |
| | | 9 | | public sealed class OrderControlEvaluationJob |
| | | 10 | | { |
| | | 11 | | public const string JobId = "order-control-evaluation"; |
| | | 12 | | public const string DefaultCron = "*/5 * * * *"; |
| | 0 | 13 | | public static string GetCron(int intervalMinutes) => $"*/{Math.Clamp(intervalMinutes, 5, 59)} * * * *"; |
| | | 14 | | private readonly IOrderControlService _service; |
| | | 15 | | private readonly ApplicationDbContext _db; |
| | | 16 | | |
| | 0 | 17 | | public OrderControlEvaluationJob(IOrderControlService service, ApplicationDbContext db) { _service = service; _db = |
| | | 18 | | |
| | | 19 | | // Hangfire-хранилище общее на двух прод-инстансах — без этого атрибута ручной RunNow |
| | | 20 | | // и очередной cron-тик могут выполниться одновременно на разных серверах. |
| | | 21 | | [Queue(HangfireQueueNames.OrderStatusSync)] |
| | | 22 | | [DisableConcurrentExecution(timeoutInSeconds: 0)] |
| | | 23 | | public async Task<int> ExecuteAsync() |
| | | 24 | | { |
| | 0 | 25 | | var settings = await _db.OrderControlSettings.FindAsync(1) ?? new OrderControlSettings { Id = 1 }; |
| | 0 | 26 | | if (_db.Entry(settings).State == EntityState.Detached) { _db.OrderControlSettings.Add(settings); await _db.SaveC |
| | 0 | 27 | | var last = await _db.OrderControlExecutions.Where(x => x.Status == "Success").OrderByDescending(x => x.Completed |
| | 0 | 28 | | if (last?.CompletedAtUtc >= DateTime.UtcNow.AddMinutes(-Math.Clamp(settings.IntervalMinutes, 5, 1440))) return 0 |
| | 0 | 29 | | var execution = new OrderControlExecution(); _db.OrderControlExecutions.Add(execution); await _db.SaveChangesAsy |
| | 0 | 30 | | try { var count = await _service.EvaluateAsync(); execution.CreatedTasksCount = count; execution.Status = "Succe |
| | 0 | 31 | | catch (Exception ex) { execution.Status = "Failed"; execution.ErrorMessage = ex.Message[..Math.Min(1000, ex.Mess |
| | 0 | 32 | | } |
| | | 33 | | } |