From 3f11e3d0ac839be942032e0e751b00b1ed976934 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=A7=E7=9F=B3=E5=A4=B4?= Date: Sat, 2 Nov 2024 10:59:27 +0800 Subject: [PATCH] =?UTF-8?q?[fix]CheckRunning=E5=90=83=E6=8E=89=E6=89=80?= =?UTF-8?q?=E6=9C=89=E7=BC=93=E5=AD=98=E5=92=8C=E6=95=B0=E6=8D=AE=E5=BA=93?= =?UTF-8?q?=E5=BC=82=E5=B8=B8=EF=BC=8C=E9=81=BF=E5=85=8D=E5=BD=B1=E5=93=8D?= =?UTF-8?q?=E6=AD=A3=E5=B8=B8=E4=B8=9A=E5=8A=A1=E3=80=82=E6=A3=80=E6=9F=A5?= =?UTF-8?q?=E6=98=AF=E5=90=A6=E6=AD=A3=E5=9C=A8=E6=89=A7=E8=A1=8C=EF=BC=8C?= =?UTF-8?q?=E5=A6=82=E6=9E=9C=E6=89=A7=E8=A1=8C=E5=88=99=E8=B7=B3=E8=BF=87?= =?UTF-8?q?=E6=9C=AC=E6=AC=A1=E5=A4=84=E7=90=86=E3=80=82fix:=20https://git?= =?UTF-8?q?hub.com/NewLifeX/NewLife.Cube/issues/98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NewLife.CubeNC/Services/JobService.cs | 39 +++++++++++++++++---------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/NewLife.CubeNC/Services/JobService.cs b/NewLife.CubeNC/Services/JobService.cs index 80641e45..0cc77e8b 100644 --- a/NewLife.CubeNC/Services/JobService.cs +++ b/NewLife.CubeNC/Services/JobService.cs @@ -268,25 +268,36 @@ public void Stop() public void Wake(Int32 ms) => _timer?.SetNext(ms); + /// 检查是否正在执行,如果执行则跳过本次处理 + /// + /// private Boolean CheckRunning(CronJob job) { - // 检查分布式锁,避免多节点重复执行 - var key = $"Job:{SysConfig.Current.Name}:{job.Id}"; - if (CacheProvider != null && !CacheProvider.Cache.Add(key, job.Name, 5)) return false; + // 吃掉所有缓存和数据库异常,避免影响正常业务 + try + { + // 检查分布式锁,避免多节点重复执行 + var key = $"Job:{SysConfig.Current.Name}:{job.Id}"; + if (CacheProvider != null && !CacheProvider.Cache.Add(key, job.Name, 5)) return true; - // 有时候可能并没有配置Redis,借助数据库事务实现去重,需要20230804版本的XCode - using var tran = CronJob.Meta.CreateTrans(); + // 有时候可能并没有配置Redis,借助数据库事务实现去重,需要20230804版本的XCode + using var tran = CronJob.Meta.CreateTrans(); - // 如果短时间内重复执行,跳过 - var job2 = CronJob.FindByKey(job.Id); - if (job2 != null && job2.LastTime.AddSeconds(5) > DateTime.Now) return false; + // 如果短时间内重复执行,跳过 + var job2 = CronJob.FindByKey(job.Id); + if (job2 != null && job2.LastTime.AddSeconds(5) > DateTime.Now) return true; - job2.LastTime = DateTime.Now; - job2.Update(); + job2.LastTime = DateTime.Now; + job2.Update(); - tran.Commit(); + tran.Commit(); - return true; + return false; + } + catch + { + return false; + } } private async void DoJobWork(Object state) @@ -294,11 +305,11 @@ private async void DoJobWork(Object state) var job = Job; // 检查分布式锁,避免多节点重复执行 - if (!CheckRunning(job)) + if (CheckRunning(job)) { var set = CubeSetting.Current; if (set.Debug) - JobService.WriteLog(job.Name, false, "分布式锁检查失败,跳过执行", job); + JobService.WriteLog(job.Name, false, "分布式锁检查到任务正在处理中,本次跳过执行", job); return; }