diff --git a/internal/app/service/task/scheduler.go b/internal/app/service/task/scheduler.go index 80a5f62..de821ee 100644 --- a/internal/app/service/task/scheduler.go +++ b/internal/app/service/task/scheduler.go @@ -256,25 +256,26 @@ func (s *Scheduler) processTask(claimedLog *models.TaskExecutionLog) { } planID := planExecutionLog.PlanID // 这才是正确的顶层计划ID - // 获取计划的最新数据 - plan, err := s.planRepo.GetPlanByID(planID) + // 获取计划的最新数据,这里我们只需要基本信息来判断执行类型和次数 + plan, err := s.planRepo.GetBasicPlanByID(planID) if err != nil { - s.logger.Errorf("获取计划 %d 的完整信息失败: %v", planID, err) + s.logger.Errorf("获取计划 %d 的基本信息失败: %v", planID, err) return } - // 更新计划的执行计数器 - plan.ExecuteCount++ + // 在内存中计算新的计数值和状态 + newExecuteCount := plan.ExecuteCount + 1 + newStatus := plan.Status // 默认为当前状态 - // 如果是自动计划且达到执行次数上限,则更新计划状态为已停止 - if (plan.ExecutionType == models.PlanExecutionTypeAutomatic && plan.ExecuteNum > 0 && plan.ExecuteCount >= plan.ExecuteNum) || plan.ExecutionType == models.PlanExecutionTypeManual { - plan.Status = models.PlanStatusStopeed - s.logger.Infof("计划 %d (自动执行) 已达到最大执行次数 %d,状态更新为 '执行完毕'。", planID, plan.ExecuteNum) + // 如果是自动计划且达到执行次数上限,或计划是手动类型,则更新计划状态为已停止 + if (plan.ExecutionType == models.PlanExecutionTypeAutomatic && plan.ExecuteNum > 0 && newExecuteCount >= plan.ExecuteNum) || plan.ExecutionType == models.PlanExecutionTypeManual { + newStatus = models.PlanStatusStopeed + s.logger.Infof("计划 %d 已完成执行,状态更新为 '执行完毕'。", planID) } - // 保存更新后的计划状态和执行计数 - if err := s.planRepo.UpdatePlan(plan); err != nil { - s.logger.Errorf("更新计划 %d 的执行计数和状态失败: %v", planID, err) + // 使用新的、专门的方法来原子性地更新计数值和状态 + if err := s.planRepo.UpdatePlanStateAfterExecution(planID, newExecuteCount, newStatus); err != nil { + s.logger.Errorf("更新计划 %d 的执行后状态失败: %v", planID, err) return } diff --git a/internal/infra/repository/plan_repository.go b/internal/infra/repository/plan_repository.go index 6dbe320..9df675c 100644 --- a/internal/infra/repository/plan_repository.go +++ b/internal/infra/repository/plan_repository.go @@ -62,6 +62,9 @@ type PlanRepository interface { // StopPlanTransactionally 停止一个计划的执行,包括更新状态、移除待执行任务和更新执行日志 StopPlanTransactionally(planID uint) error + + // UpdatePlanStateAfterExecution 更新计划执行后的状态(计数和状态) + UpdatePlanStateAfterExecution(planID uint, newCount uint, newStatus models.PlanStatus) error } // gormPlanRepository 是 PlanRepository 的 GORM 实现 @@ -735,3 +738,10 @@ func (r *gormPlanRepository) UpdatePlanStatus(id uint, status models.PlanStatus) } return nil } + +func (r *gormPlanRepository) UpdatePlanStateAfterExecution(planID uint, newCount uint, newStatus models.PlanStatus) error { + return r.db.Model(&models.Plan{}).Where("id = ?", planID).Updates(map[string]interface{}{ + "execute_count": newCount, + "status": newStatus, + }).Error +}