| | 1 | | using Quartz; |
| | 2 | | using Microsoft.EntityFrameworkCore.Diagnostics; |
| | 3 | | using Microsoft.EntityFrameworkCore.Infrastructure; |
| | 4 | |
|
| | 5 | | namespace Syki.Back.Database.Interceptors; |
| | 6 | |
|
| | 7 | | public sealed class CommandsDelayInterceptor : SaveChangesInterceptor |
| | 8 | | { |
| 13776 | 9 | | private List<DateTime> _delays = []; |
| | 10 | |
|
| | 11 | | public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, Interception |
| | 12 | | { |
| 15320 | 13 | | _delays = eventData.Context.ChangeTracker |
| 15320 | 14 | | .Entries<Command>() |
| 5376 | 15 | | .Where(entry => entry.State == EntityState.Added && entry.Entity.NotBefore != null) |
| 0 | 16 | | .Select(x => x.Entity.NotBefore!.Value) |
| 15320 | 17 | | .ToList(); |
| | 18 | |
|
| 30640 | 19 | | return await Task.Run(() => result); |
| 15320 | 20 | | } |
| | 21 | |
|
| | 22 | | public override async ValueTask<int> SavedChangesAsync(SaveChangesCompletedEventData eventData, int result, Cancella |
| | 23 | | { |
| 30640 | 24 | | if (_delays.Count == 0) return result; |
| | 25 | |
|
| 0 | 26 | | var schedulerFactory = eventData.Context.GetService<ISchedulerFactory>(); |
| 0 | 27 | | var scheduler = await schedulerFactory.GetScheduler(cancellationToken); |
| | 28 | |
|
| 0 | 29 | | foreach (var delay in _delays) |
| | 30 | | { |
| 0 | 31 | | var job = JobBuilder.Create<NotifyNewCommandJob>().Build(); |
| 0 | 32 | | var trigger = Quartz.TriggerBuilder.Create() |
| 0 | 33 | | .StartAt(delay) |
| 0 | 34 | | .Build(); |
| 0 | 35 | | await scheduler.ScheduleJob(job, trigger, cancellationToken); |
| | 36 | | } |
| | 37 | |
|
| 0 | 38 | | return result; |
| 15320 | 39 | | } |
| | 40 | | } |
| | 41 | |
|
| | 42 | | public class NotifyNewCommandJob(SykiDbContext ctx) : IJob |
| | 43 | | { |
| | 44 | | public async Task Execute(IJobExecutionContext context) |
| | 45 | | { |
| | 46 | | await ctx.Database.ExecuteSqlRawAsync($"NOTIFY new_command", context.CancellationToken); |
| | 47 | | } |
| | 48 | | } |