Merge branch 'master' into net6.0

This commit is contained in:
不做码农
2022-03-17 21:38:30 +08:00
17 changed files with 422 additions and 368 deletions

View File

@@ -23,6 +23,6 @@ namespace ZR.Tasks
Task<ApiResult> RunTaskScheduleAsync(SysTasksQz tasksQz);
Task<ApiResult> UpdateTaskScheduleAsync(SysTasksQz tasksQz, string groupName);
Task<ApiResult> UpdateTaskScheduleAsync(SysTasksQz tasksQz);
}
}

View File

@@ -2,7 +2,6 @@
using NLog;
using Quartz;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using ZR.Model.System;
@@ -22,7 +21,7 @@ namespace ZR.Tasks
/// </summary>
/// <param name="context">作业上下文</param>
/// <param name="job">业务逻辑方法</param>
public async Task<Dictionary<string,object>> ExecuteJob(IJobExecutionContext context, Func<Task> job)
public async Task<SysTasksLog> ExecuteJob(IJobExecutionContext context, Func<Task> job)
{
double elapsed = 0;
int status = 0;
@@ -37,54 +36,54 @@ namespace ZR.Tasks
await job();
stopwatch.Stop();
elapsed = stopwatch.Elapsed.TotalMilliseconds;
logMsg = "Succeed";
logMsg = "success";
}
catch (Exception ex)
{
JobExecutionException e2 = new JobExecutionException(ex);
//true 是立即重新执行任务
e2.RefireImmediately = true;
JobExecutionException e2 = new(ex)
{
//true 是立即重新执行任务
RefireImmediately = true
};
status = 1;
logMsg = $"FailException{ex.Message}";
}
Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("elapsed", elapsed);
dic.Add("status", status);
dic.Add("content", logMsg);
RecordTaskLog(context, dic);
return dic;
var logModel = new SysTasksLog()
{
Elapsed = elapsed,
Status = status.ToString(),
JobMessage = logMsg
};
RecordTaskLog(context, logModel);
return logModel;
}
/// <summary>
/// 记录到日志
/// </summary>
/// <param name="context"></param>
/// <param name="executeLog"></param>
protected void RecordTaskLog(IJobExecutionContext context, Dictionary<string, object> executeLog)
/// <param name="logModel"></param>
protected void RecordTaskLog(IJobExecutionContext context, SysTasksLog logModel)
{
var tasksLogService = (ISysTasksLogService)App.GetRequiredService(typeof(ISysTasksLogService));
var taskQzService = (ISysTasksQzService)App.GetRequiredService(typeof(ISysTasksQzService));
// 可以直接获取 JobDetail 的值
IJobDetail job = context.JobDetail;
//var param = context.MergedJobDataMap;
// 也可以通过数据库配置,获取传递过来的参数
//JobDataMap data = context.JobDetail.JobDataMap;
//int jobId = data.GetInt("JobParam");
var logModel = new SysTasksLog();
logModel.InvokeTarget = job.JobType.FullName;
logModel.Elapsed = (double)executeLog.GetValueOrDefault("elapsed", "0");
logModel.JobMessage = executeLog.GetValueOrDefault("content").ToString();
logModel.Status = executeLog.GetValueOrDefault("status", "0").ToString();
logModel = tasksLogService.AddTaskLog(job.Key.Name, logModel);
taskQzService.Update(f => f.ID == job.Key.Name, f => new SysTasksQz()
//成功后执行次数+1
if (logModel.Status == "0")
{
RunTimes = f.RunTimes + 1
});
taskQzService.Update(f => f.ID == job.Key.Name, f => new SysTasksQz()
{
RunTimes = f.RunTimes + 1,
LastRunTime = DateTime.Now
});
}
logger.Info($"执行任务【{job.Key.Name}|{logModel.JobName}】结果={logModel.JobMessage}");
}
}

View File

@@ -1,11 +1,14 @@
using Quartz;
using Infrastructure.Attribute;
using Quartz;
using System.Threading.Tasks;
namespace ZR.Tasks
namespace ZR.Tasks.TaskScheduler
{
/// <summary>
/// 定时任务测试
/// 使用如下注册后TaskExtensions里面不用再注册了
/// </summary>
[AppService(ServiceType = typeof(Job_SyncTest), ServiceLifetime = LifeTime.Scoped)]
public class Job_SyncTest : JobBase, IJob
{
//private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
@@ -20,6 +23,7 @@ namespace ZR.Tasks
await Task.Delay(1);
//TODO 业务逻辑
System.Console.WriteLine("job test");
}
}
}

View File

@@ -2,10 +2,13 @@
using NLog;
using Quartz;
using Quartz.Impl;
using Quartz.Impl.Matchers;
using Quartz.Impl.Triggers;
using Quartz.Spi;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using ZR.Model.System;
@@ -60,7 +63,7 @@ namespace ZR.Tasks
};
StdSchedulerFactory factory = new StdSchedulerFactory(collection);
return _scheduler = factory.GetScheduler();
}
@@ -153,11 +156,15 @@ namespace ZR.Tasks
trigger = CreateCronTrigger(tasksQz);
//解决Quartz启动后第一次会立即执行问题解决办法
((CronTriggerImpl)trigger).MisfireInstruction = MisfireInstruction.CronTrigger.DoNothing;
// 5、将触发器和任务器绑定到调度器中
await _scheduler.Result.ScheduleJob(job, trigger);
}
else
{
trigger = CreateSimpleTrigger(tasksQz);
((SimpleTriggerImpl)trigger).MisfireInstruction = MisfireInstruction.CronTrigger.DoNothing;
}
// 5、将触发器和任务器绑定到调度器中
await _scheduler.Result.ScheduleJob(job, trigger);
//任务没有启动、暂停任务
if (!tasksQz.IsStart)
{
@@ -252,8 +259,19 @@ namespace ZR.Tasks
try
{
JobKey jobKey = new JobKey(tasksQz.ID, tasksQz.JobGroup);
List<JobKey> jobKeys = _scheduler.Result.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(tasksQz.JobGroup)).Result.ToList();
if (jobKeys == null || jobKeys.Count == 0)
{
return new ApiResult(110, $"未找到分组[{ tasksQz.JobGroup }]");
}
var triggers = await _scheduler.Result.GetTriggersOfJob(jobKey);
if (triggers.Count <= 0)
{
return new ApiResult(110, $"未找到触发器[{jobKey.Name}]");
}
await _scheduler.Result.TriggerJob(jobKey);
return ApiResult.Success($"运行计划任务:【{tasksQz.Name}】成功");
}
catch (Exception ex)
@@ -267,11 +285,11 @@ namespace ZR.Tasks
/// </summary>
/// <param name="tasksQz"></param>
/// <returns></returns>
public async Task<ApiResult> UpdateTaskScheduleAsync(SysTasksQz tasksQz, string groupName)
public async Task<ApiResult> UpdateTaskScheduleAsync(SysTasksQz tasksQz)
{
try
{
JobKey jobKey = new JobKey(tasksQz.ID, groupName);
JobKey jobKey = new JobKey(tasksQz.ID, tasksQz.JobGroup);
if (await _scheduler.Result.CheckExists(jobKey))
{
//防止创建时存在数据问题 先移除,然后在执行创建操作
@@ -294,33 +312,30 @@ namespace ZR.Tasks
/// </summary>
/// <param name="tasksQz"></param>
/// <returns></returns>
//private ITrigger CreateSimpleTrigger(SysTasksQz tasksQz)
//{
// if (tasksQz.RunTimes > 0)
// {
// ITrigger trigger = TriggerBuilder.Create()
// .WithIdentity(tasksQz.ID, tasksQz.JobGroup)
// .StartAt(tasksQz.BeginTime.Value)
// .EndAt(tasksQz.EndTime.Value)
// .WithSimpleSchedule(x =>
// x.WithIntervalInSeconds(tasksQz.IntervalSecond)
// .WithRepeatCount(tasksQz.RunTimes)).ForJob(tasksQz.ID, tasksQz.JobGroup).Build();
// return trigger;
// }
// else
// {
// ITrigger trigger = TriggerBuilder.Create()
// .WithIdentity(tasksQz.ID, tasksQz.JobGroup)
// .StartAt(tasksQz.BeginTime.Value)
// .EndAt(tasksQz.EndTime.Value)
// .WithSimpleSchedule(x =>
// x.WithIntervalInSeconds(tasksQz.IntervalSecond)
// .RepeatForever()).ForJob(tasksQz.ID, tasksQz.JobGroup).Build();
// return trigger;
// }
// // 触发作业立即运行然后每10秒重复一次无限循环
//}
private ITrigger CreateSimpleTrigger(SysTasksQz tasksQz)
{
if (tasksQz.RunTimes > 0)
{
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity(tasksQz.ID, tasksQz.JobGroup)
.StartAt(tasksQz.BeginTime.Value)
.EndAt(tasksQz.EndTime.Value)
.WithSimpleSchedule(x => x.WithIntervalInSeconds(tasksQz.IntervalSecond)
.WithRepeatCount(tasksQz.RunTimes)).ForJob(tasksQz.ID, tasksQz.JobGroup).Build();
return trigger;
}
else
{
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity(tasksQz.ID, tasksQz.JobGroup)
.StartAt(tasksQz.BeginTime.Value)
.EndAt(tasksQz.EndTime.Value)
.WithSimpleSchedule(x => x.WithIntervalInSeconds(tasksQz.IntervalSecond)
.RepeatForever()).ForJob(tasksQz.ID, tasksQz.JobGroup).Build();
return trigger;
}
// 触发作业立即运行然后每10秒重复一次无限循环
}
/// <summary>
/// 创建类型Cron的触发器