一 安装包
Install-Package Quartz.Extensions.Hosting
二 注入依赖关系
services.AddQuartz(configure => { configure.UseMicrosoftDependencyInjectionJobFactory(); }); services.AddQuartzHostedService(options => { options.WaitForJobsToComplete = true; });
三 添加Job任务
[DisallowConcurrentExecution] public class ProcessOutboxMessagesJob : IJob { private readonly ApplicationDbContext _dbContext; private readonly IPublisher _publisher; public ProcessOutboxMessagesJob( ApplicationDbContext dbContext, IPublisher publisher) { _dbContext = dbContext; _publisher = publisher; } public async Task Execute(IJobExecutionContext context) { List<OutboxMessage> messages = await _dbContext .Set<OutboxMessage>() .Where(m => m.ProcessedOnUtc == null) .Take(20) .ToListAsync(context.CancellationToken); foreach (OutboxMessage outboxMessage in messages) { IDomainEvent? domainEvent = JsonConvert .DeserializeObject<IDomainEvent>( outboxMessage.Content, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }); if (domainEvent is null) { continue; } await _publisher.Publish(domainEvent, context.CancellationToken); outboxMessage.ProcessedOnUtc = DateTime.UtcNow; await _dbContext.SaveChangesAsync(); } } }
四 Services中添加任务。
services.AddQuartz(configure => { var jobKey = new JobKey(nameof(ProcessOutboxMessagesJob)); configure .AddJob<ProcessOutboxMessagesJob>(jobKey) .AddTrigger( trigger => trigger.ForJob(jobKey).WithSimpleSchedule( schedule => schedule.WithIntervalInSeconds(10).RepeatForever())); configure.UseMicrosoftDependencyInjectionJobFactory(); });
标签:core,Quartz,Jobs,configure,publisher,dbContext,ProcessOutboxMessagesJob,jobKey From: https://www.cnblogs.com/Insist-Y/p/17461923.html