public TaskServicesRunner() { //获取默认任务调度器 scheduler = StdSchedulerFactory.GetDefaultScheduler(); majorTaskInfo = new TB_TM_TaskInfo() { TaskId = -1, TaskType = TaskType.IJob.ToString(), TaskName = System.Configuration.ConfigurationManager.AppSettings["MajorTaskName"], Description = System.Configuration.ConfigurationManager.AppSettings["MajorTaskDescription"], CronExpression = System.Configuration.ConfigurationManager.AppSettings["MajorTaskCronExpression"], CronExpressionDescription = System.Configuration.ConfigurationManager.AppSettings["MajorTaskCronExpressionDescription"], }; //scheduler.ListenerManager.AddSchedulerListener(new SchedulerListener()); scheduler.ListenerManager.AddJobListener(new SchedulerJobListener(), GroupMatcher <JobKey> .GroupStartsWith("TaskGroup.")); var job = JobBuilder.Create <MajorTask>() .WithIdentity(majorTaskInfo.TaskName + ".TaskName", majorTaskInfo.TaskName + ".TaskGroup") .Build(); job.JobDataMap.Add("TaskInfo", JsonConvert.SerializeObject(majorTaskInfo)); var trigger = TriggerBuilder.Create() .StartNow() .WithIdentity(majorTaskInfo.TaskName + ".TriggerName", majorTaskInfo.TaskName + ".TriggerGroup") .WithCronSchedule(majorTaskInfo.CronExpression) .Build(); scheduler.ScheduleJob(job, trigger); }
public ActionResult AddPost(TB_TM_TaskInfo Info) { var result = new ResponseResult(); //Info.BackgroundJobId = System.Guid.NewGuid(); result.success = _TaskInfoService.Add(Info); return(Json(result)); }
public ActionResult UpatePost(TB_TM_TaskInfo Info) { var result = new ResponseResult(); result.success = _TaskInfoService.Update(Info); result.message = result.success == true ? "操作成功" : "操作失败"; return(Json(result)); }
/// <summary> /// Job调度 /// </summary> /// <param name="scheduler"></param> /// <param name="taskInfo"></param> public static bool AddScheduleJob(IScheduler scheduler, TB_TM_TaskInfo taskInfo) { bool addFlag = false; if (ValidExpression(taskInfo.CronExpression)) { Type type = null; if (taskInfo.TaskType == TaskType.IJob.ToString()) { type = GetClassInfo(taskInfo.AssemblyName, taskInfo.ClassName); } else if (taskInfo.TaskType == TaskType.Exe.ToString() || taskInfo.TaskType == TaskType.Url.ToString()) { type = typeof(ProxyTask); } else { WriteTaskLog(taskInfo, "TaskType:[" + taskInfo.TaskType + "]不正确,无法启动该任务", TaskState.Error); } if (type != null) { try { var job = JobBuilder.Create(type) .WithIdentity("TaskName." + taskInfo.TaskId, "TaskGroup." + taskInfo.TaskId) .WithDescription(taskInfo.Description)//任务描述 .Build(); job.JobDataMap.Add("TaskInfo", JsonConvert.SerializeObject(taskInfo)); var trigger = TriggerBuilder.Create() .WithIdentity("TriggerName." + taskInfo.TaskId, "TriggerGroup." + taskInfo.TaskId) .WithDescription(taskInfo.Description) //任务描述 //FirstRunTime 就按照这个时间直接,否则立刻执行 .StartAt(taskInfo.FirstRunTime.HasValue ? taskInfo.FirstRunTime.Value : DateTime.Now) .WithPriority(taskInfo.Priority + 5) //5是trigger默认优先级 //.StartNow() .WithCronSchedule(taskInfo.CronExpression) .Build(); scheduler.ScheduleJob(job, trigger); addFlag = true; } catch (Exception ex) { WriteTaskLog(taskInfo, "创建任务异常:[" + ex.Message + "],无法启动该任务", TaskState.Error); } } else { WriteTaskLog(taskInfo, "AssemblyName:[" + taskInfo.AssemblyName + ",ClassName:" + taskInfo.ClassName + "]无效,无法启动该任务", TaskState.Error); } } else { WriteTaskLog(taskInfo, "CronExpression:[" + taskInfo.CronExpression + "]不正确,无法启动该任务", TaskState.Error); } return(addFlag); }
/// <summary> /// 任务失败写log表,并调整任务状态是Error /// </summary> /// <param name="taskInfo"></param> /// <param name="runLog"></param> private static void WriteTaskLog(TB_TM_TaskInfo taskInfo, string runLog, TaskState taskState) { new TaskLogService().Add(new TaskManager.Core.Model.TB_TM_TaskLog() { TaskId = taskInfo.TaskId, TaskName = taskInfo.TaskName, ExecutionDuration = 0, CreatedDateTime = DateTime.Now, ExecutionTime = DateTime.Now, RunLog = runLog }); taskInfo.State = (int)taskState; new TaskInfoService().Update(taskInfo); }
public void JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException) { try { //DateTime? NextFireTimeUtc = TimeZoneInfo.ConvertTimeFromUtc(context.NextFireTimeUtc.Value.DateTime, TimeZoneInfo.Local); //DateTime? FireTimeUtc = TimeZoneInfo.ConvertTimeFromUtc(context.FireTimeUtc.Value.DateTime, TimeZoneInfo.Local); DateTime?NextFireTimeUtc = null; if (context.NextFireTimeUtc.HasValue) { NextFireTimeUtc = context.NextFireTimeUtc.Value.DateTime; } DateTime?FireTimeUtc = null; if (context.NextFireTimeUtc.HasValue) { FireTimeUtc = context.FireTimeUtc.Value.DateTime; } double TotalSeconds = context.JobRunTime.TotalSeconds; TB_TM_TaskInfo taskInfo = null; string LogContent = string.Empty; if (context.MergedJobDataMap != null) { if (context.MergedJobDataMap.ContainsKey("TaskInfo")) { taskInfo = JsonConvert.DeserializeObject <TB_TM_TaskInfo>(context.MergedJobDataMap.GetString("TaskInfo")); } if (taskInfo != null) { System.Text.StringBuilder log = new System.Text.StringBuilder(); int i = 0; foreach (var item in context.MergedJobDataMap) { string key = item.Key; if (key.StartsWith("Extend_")) { if (i > 0) { log.Append(","); } log.AppendFormat("{0}:{1}", item.Key, item.Value); i++; } } if (i > 0) { LogContent = string.Concat("[", log.ToString(), "]"); } TaskInfoService _TaskInfoService = new TaskInfoService(); TaskLogService _TaskLogService = new TaskLogService(); taskInfo = _TaskInfoService.GetModel(taskInfo.TaskId); taskInfo.LastRunTime = FireTimeUtc; taskInfo.NextRunTime = NextFireTimeUtc; taskInfo.RunCount = taskInfo.RunCount + 1; if (taskInfo.ImmedRun == 1)//立刻运行 { LogContent = "(本次是立刻运行)" + LogContent; taskInfo.ImmedRun = 0; } _TaskInfoService.Update(taskInfo); _TaskLogService.Add(new TaskManager.Core.Model.TB_TM_TaskLog() { TaskId = taskInfo.TaskId, TaskName = taskInfo.TaskName, CreatedDateTime = DateTime.Now, ExecutionTime = FireTimeUtc, ExecutionDuration = TotalSeconds, RunLog = LogContent }); } } //if (jobException != null) //{ // LogContent = LogContent + " EX:" + jobException.ToString(); // new TaskLogService().Add(new TaskManager.Core.Model.TB_TM_TaskLog() // { // TaskId = Convert.ToInt32(TaskId), // TaskName = TaskName, // CreatedDateTime = DateTime.Now, // ExecutionTime = FireTimeUtc, // ExecutionDuration = TotalSeconds, // RunLog = LogContent // }); //} } catch (Exception ex) { //错误日志 } }
public void Execute(IJobExecutionContext context) { var jobDataMap = context.JobDetail.JobDataMap; TB_TM_TaskInfo taskInfo = null; if (jobDataMap != null) { if (jobDataMap.ContainsKey("TaskInfo")) { taskInfo = JsonConvert.DeserializeObject <TB_TM_TaskInfo>(jobDataMap.GetString("TaskInfo")); } if (taskInfo != null) { if (taskInfo.TaskType == TaskType.Exe.ToString()) { #region Exe Job try { //参数设置 string arguments = string.Empty; if (!string.IsNullOrEmpty(taskInfo.TaskArgs)) { var tmpDic = JsonConvert.DeserializeObject <Dictionary <string, string> >(taskInfo.TaskArgs); arguments = string.Join(" ", tmpDic.Values);//空格分隔 } System.Diagnostics.Process exep = new System.Diagnostics.Process(); exep.StartInfo.ErrorDialog = false;//错误窗口不显示 exep.StartInfo.UseShellExecute = false; exep.StartInfo.RedirectStandardOutput = true; exep.StartInfo.RedirectStandardError = true; // 重定向错误输出 exep.StartInfo.FileName = QuartzManager.GetAbsolutePath(taskInfo.AssemblyName); //exe 文件地址 exep.StartInfo.CreateNoWindow = true; exep.StartInfo.Arguments = arguments; //参数以空格分隔,如果某个参数为空,可以传入”” exep.Start(); exep.WaitForExit(); //关键,等待外部程序退出后才能往下执行 string output = exep.StandardOutput.ReadToEnd(); context.MergedJobDataMap.Add("Extend_" + taskInfo.TaskType + "_Return", output); //错误 string error = exep.StandardError.ReadToEnd(); if (!string.IsNullOrEmpty(error)) { context.MergedJobDataMap.Add("Extend_" + taskInfo.TaskType + "_Error", error); } } catch (Exception ex) { context.MergedJobDataMap.Add("Extend_" + taskInfo.TaskType + "_Exception", ex.Message); } #endregion Exe Job } else if (taskInfo.TaskType == TaskType.Url.ToString()) { #region Url Job try { //参数设置 Dictionary <string, string> argsDic = new Dictionary <string, string>(); if (!string.IsNullOrEmpty(taskInfo.TaskArgs) && taskInfo.TaskArgs.Contains(",")) { argsDic = JsonConvert.DeserializeObject <Dictionary <string, string> >(taskInfo.TaskArgs); } var Response = HttpHelper.CreatePostHttpResponse(taskInfo.AssemblyName, argsDic); if (Response != null) { context.MergedJobDataMap.Add("Extend_" + taskInfo.TaskType + "_Return", "Code:" + Response.StatusCode + "--Description:" + Response.StatusDescription); //错误 if (Response.StatusCode != System.Net.HttpStatusCode.OK) { context.MergedJobDataMap.Add("Extend_" + taskInfo.TaskType + "_Error", HttpHelper.GetResponseString(Response)); } } else { throw new Exception("Response返回null"); } } catch (Exception ex) { context.MergedJobDataMap.Add("Extend_" + taskInfo.TaskType + "_Exception", ex.Message); } #endregion Url Job } } } }