使用Quartz.net的时候经常会遇到一种情况,就是job执行速度过慢,而Quartz.net默认也是并发执行的,这就导致一种情况,之前的job还没做完,第二个就开始了,在某些业务场景下这种情况容易造成数据错乱,那么这个时候就需要把执行改成单线程执行,解决起来很简单,就是在job类加注解[DisallowConcurrentExecutionAttribute]
具体实现方式如下,以abp vnext 实现的quartz.net为例子:
[DisallowConcurrentExecutionAttribute] public class QueryWork : QuartzBackgroundWorkerBase { private IAppService _appService; public QueryWork(IAppService appService) { _appService = appService; JobDetail = JobBuilder.Create<QueryWork>().WithIdentity(nameof(QueryWork)).Build(); Trigger = TriggerBuilder.Create().WithIdentity(nameof(QueryWork)) .WithDailyTimeIntervalSchedule(s => s.WithIntervalInSeconds(5)).Build(); } public async override Task Execute(IJobExecutionContext context) { await _appService.QueryAsync(); } }