/// <summary> /// 执行任务的回调函数 /// </summary> /// <param name="result"></param> private static void CallBackOfDoJob(IAsyncResult result) { TaskInfo task = (TaskInfo)result.AsyncState; try { DoJobDelegate del = (DoJobDelegate)task.ExternOperationObject; del.EndInvoke(result); } catch (Exception ex) { task.ErrorTimesOfNowOperation = task.ErrorTimesOfNowOperation + 1; //失败执行写入日志 ServiceLog.SaveLog("执行任务(CallBackOfDoJob):" + task.TaskName + "失败!" + DateTime.Now.ToString() + "\r\n" + ex.Message + "\r\n" + ex.StackTrace + "\r\n"); } finally { task.IsExecuting = false; task.LastExecuteTime = DateTime.Now; } }
/// <summary> /// 轮询线程的入口 /// </summary> public static void PollingThreadEntrance() { while (RuntimeInfo.ContinueWork) { for (int i = 0; i < 60 && RuntimeInfo.ContinueWork; i++) { Thread.Sleep(1000); } //每隔1分钟进行一次调度 if (RuntimeInfo.ContinueWork) { for (int i = 0; i < TaskInfoList.Count; i++) { TaskInfo theTaskInfo = TaskInfoList[i]; if (theTaskInfo.IsExecuting) { continue; } var taskConfig = theTaskInfo.ConfigOfTask; string timeTag = GetTimeTagOfLatestOperation(theTaskInfo); if (string.IsNullOrEmpty(theTaskInfo.TimeTagOfNowOperation)) { theTaskInfo.TimeTagOfNowOperation = timeTag; } StringBuilder logBuffer = new StringBuilder(); logBuffer.Append("调度任务:本次计算所得的调度时间为[").Append(timeTag).Append("],"); logBuffer.Append("任务已执行的调度时间为[").Append(theTaskInfo.TimeTagOfNowOperation).AppendLine("]。"); bool doJob = false; TimeSpan tsToLastExecute; switch (taskConfig.LoopType) { case TaskLoopType.NotLoop: if (!theTaskInfo.HaveExecuteIfNotLoop) { doJob = true; } break; case TaskLoopType.SecondInterval: tsToLastExecute = DateTime.Now.Subtract(theTaskInfo.LastExecuteTime); if (tsToLastExecute.TotalSeconds > taskConfig.LoopInterval) { doJob = true; } break; case TaskLoopType.PerDay: case TaskLoopType.PerHour: case TaskLoopType.PerMonth: case TaskLoopType.PerWeek: if (timeTag != theTaskInfo.TimeTagOfNowOperation) { theTaskInfo.TimeTagOfNowOperation = timeTag; doJob = true; } else if (!theTaskInfo.IsSuccessOfNowOperation && theTaskInfo.ErrorTimesOfNowOperation < taskConfig.TryTimesIfFailure) { tsToLastExecute = DateTime.Now.Subtract(theTaskInfo.LastExecuteTime); if (tsToLastExecute.TotalSeconds > taskConfig.TryIntervalAfterFailure) { logBuffer.AppendLine("当前为失败后重试"); doJob = true; } } break; default: break; } if (doJob) { logBuffer.AppendLine("经过计算,本次轮询将执行任务新的轮次"); DoJobDelegate del = new DoJobDelegate(DoJob); theTaskInfo.IsExecuting = true; theTaskInfo.ExternOperationObject = del; del.BeginInvoke(theTaskInfo, new AsyncCallback(CallBackOfDoJob), theTaskInfo); } else { logBuffer.AppendLine("本次轮询不执行任务"); } ServiceLog.SaveDebugLog(theTaskInfo.TaskName, logBuffer.ToString()); } } } }
public JobScheduler(DoJobDelegate del) { ExecuteJobAction = del; }