🎈fix(定时任务): 修复分布式场景下,定时任务被重复执行的问题

This commit is contained in:
喵你个汪呀 2025-08-30 23:11:50 +08:00
parent fd07c3862a
commit 4c35b196ad
2 changed files with 21 additions and 1 deletions

View File

@ -135,4 +135,9 @@ public class CacheConst
/// 流水号类型
/// </summary>
public const string KeySysSerialType = "sys_serial_type";
/// <summary>
/// 定时任务分布式锁缓存
/// </summary>
public const string KeyDisLockJob = "dis_lock_job:";
}

View File

@ -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}";