public IActionResult ManualStart([FromBody] Plan plan) { try { if (plan != null) { _logger.LogInformation("启动预案{0}Begin......", plan.PlanId); //if (PlanTaskScheduler.Instance.PlanIsRunning(plan.PlanId)) //待定,运行的任务是否要再启动 //{ //_logger.LogInformation("预案{0}已启动,取消执行......", plan.PlanId); //return Ok("预案已启动"); //} TimePeriod tp = new TimePeriod() { StartTime = DateTime.Now, EndTime = DateTime.MaxValue }; PlanTaskWrapper task = new PlanTaskWrapper() { Plan = plan, RunTimePeriod = tp, TaskId = Guid.NewGuid(), }; PlanExecutor executor = new PlanExecutor(task); PlanTaskScheduler.Instance.AddPlanExecutorToCache(executor); executor.Start(); _logger.LogInformation("启动预案{0}End......", plan.PlanId); return(Ok()); } else { return(NotFound()); } } catch (Exception ex) { _logger.LogError("启动预案异常:Message:{0}\r\nStackTrace:{1}", ex.Message, ex.StackTrace); return(BadRequest(ex.Message)); } }
private void Run() { while (true) { try { TimerTask executeTask = m_timerTaskList.OrderBy(t => t.TaskSchedule.ScheduleCycle.NextExecute).FirstOrDefault(t => !t.Running); if (executeTask == null) { m_planExecutorWaiter.WaitOne(); } //休眠 Schedule planSchedule = executeTask.TaskSchedule; DateTime currTime = DateTime.Now; //if (planSchedule.ScheduleCycle.NextExecute == null || !executePlan.Running) //任务服务重启的情况 //{ // //更新执行时间 // SetPlanNextExecute(planSchedule, currTime); //} if (planSchedule.ScheduleCycle.NextExecute != null) { int waitTimeout = (int)((planSchedule.ScheduleCycle.NextExecute.Value - currTime).TotalMilliseconds); //误差2分钟内,有效执行 if (waitTimeout < 0 && waitTimeout > -2 * 60 * 1000) { waitTimeout = 0; } if (waitTimeout >= 0) { _logger.LogInformation("等待{0}ms后将执行预案....", waitTimeout); TimePeriod tp = ScheduleUtility.GetPlanTaskTimePeriod(planSchedule, planSchedule.ScheduleCycle.NextExecute.Value); // 运行预案 PlanTaskWrapper task = new PlanTaskWrapper() { Plan = executeTask.Plan, RunTimePeriod = tp, TaskId = executeTask.TimerTaskId }; PlanExecutor executor = new PlanExecutor(task); executor.OnPlanExecutedEnd += Executor_OnPlanExecutedEnd; executeTask.Running = true; var planTask = Task.Delay(waitTimeout).ContinueWith((runTask) => executor.Start()); AddPlanExecutorToCache(executor); } } } catch (Exception ex) { _logger.LogError("执行预案异常:Message:{0}\r\nStackTrace:{1}", ex.Message, ex.StackTrace); } } }