Merge pull request '🎈fix(定时任务): 修复分布式场景下,定时任务被重复执行的问题' (#435) from jasondom/Admin.NET.Pro:v2 into v2
Reviewed-on: https://code.adminnet.top/Admin.NET/Admin.NET.Pro/pulls/435
This commit is contained in:
commit
f3b483506f
@ -135,4 +135,9 @@ public class CacheConst
|
||||
/// 流水号类型
|
||||
/// </summary>
|
||||
public const string KeySysSerialType = "sys_serial_type";
|
||||
|
||||
/// <summary>
|
||||
/// 定时任务分布式锁缓存
|
||||
/// </summary>
|
||||
public const string KeyDisLockJob = "dis_lock_job:";
|
||||
}
|
||||
@ -11,25 +11,40 @@ namespace Admin.NET.Core.Service;
|
||||
/// </summary>
|
||||
public class JobMonitor : IJobMonitor
|
||||
{
|
||||
private readonly Dictionary<string, IDisposable> _jobLocks = new();
|
||||
private readonly SysConfigService _sysConfigService;
|
||||
private readonly SysCacheService _sysCacheService;
|
||||
private readonly IEventPublisher _eventPublisher;
|
||||
private readonly ILogger<JobMonitor> _logger;
|
||||
|
||||
public JobMonitor(IServiceScopeFactory serviceScopeFactory, IEventPublisher eventPublisher, ILogger<JobMonitor> logger)
|
||||
public JobMonitor(IServiceScopeFactory serviceScopeFactory, SysCacheService sysCacheService, IEventPublisher eventPublisher, ILogger<JobMonitor> logger)
|
||||
{
|
||||
var serviceScope = serviceScopeFactory.CreateScope();
|
||||
_sysConfigService = serviceScope.ServiceProvider.GetRequiredService<SysConfigService>();
|
||||
_sysCacheService = sysCacheService;
|
||||
_eventPublisher = eventPublisher;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public Task OnExecutingAsync(JobExecutingContext context, CancellationToken stoppingToken)
|
||||
{
|
||||
var key = $"{CacheConst.KeyDisLockJob}{context.JobId}";
|
||||
var dis = _sysCacheService.BeginCacheLock(key);
|
||||
if (dis == null) return Task.FromCanceled(stoppingToken);
|
||||
|
||||
_jobLocks[key] = dis;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public async Task OnExecutedAsync(JobExecutedContext context, CancellationToken stoppingToken)
|
||||
{
|
||||
var key = $"{CacheConst.KeyDisLockJob}{context.JobId}";
|
||||
if (_jobLocks.TryGetValue(key, out var dis))
|
||||
{
|
||||
dis.Dispose();
|
||||
_jobLocks.Remove(key);
|
||||
}
|
||||
|
||||
if (context.Exception == null) return;
|
||||
|
||||
var exception = $"定时任务【{context.Trigger.Description}】错误:{context.Exception}";
|
||||
|
||||
Loading…
Reference in New Issue
Block a user