初始刷
This commit is contained in:
137
ZR.Tasks/TaskScheduler/JobBase.cs
Normal file
137
ZR.Tasks/TaskScheduler/JobBase.cs
Normal file
@@ -0,0 +1,137 @@
|
||||
using Infrastructure;
|
||||
using NLog;
|
||||
using Quartz;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Threading.Tasks;
|
||||
using ZR.Common;
|
||||
using ZR.Model.System;
|
||||
using ZR.ServiceCore.Services;
|
||||
|
||||
namespace ZR.Tasks
|
||||
{
|
||||
public class JobBase
|
||||
{
|
||||
/// <summary>
|
||||
/// 日志接口
|
||||
/// </summary>
|
||||
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
|
||||
|
||||
/// <summary>
|
||||
/// 执行指定任务
|
||||
/// </summary>
|
||||
/// <param name="context">作业上下文</param>
|
||||
/// <param name="job">业务逻辑方法</param>
|
||||
public async Task<SysTasksLog> ExecuteJob(IJobExecutionContext context, Func<Task> job)
|
||||
{
|
||||
double elapsed = 0;
|
||||
int status = 0;
|
||||
string logMsg;
|
||||
try
|
||||
{
|
||||
//var s = context.Trigger.Key.Name;
|
||||
//记录Job时间
|
||||
Stopwatch stopwatch = new Stopwatch();
|
||||
stopwatch.Start();
|
||||
//执行任务
|
||||
await job();
|
||||
stopwatch.Stop();
|
||||
elapsed = stopwatch.Elapsed.TotalMilliseconds;
|
||||
logMsg = "success";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
JobExecutionException e2 = new(ex)
|
||||
{
|
||||
//true 是立即重新执行任务
|
||||
RefireImmediately = true
|
||||
};
|
||||
status = 1;
|
||||
logMsg = $"Job Run Fail,Exception:{ex.Message}";
|
||||
WxNoticeHelper.SendMsg("任务执行出错", logMsg);
|
||||
}
|
||||
|
||||
var logModel = new SysTasksLog()
|
||||
{
|
||||
Elapsed = elapsed,
|
||||
Status = status.ToString(),
|
||||
JobMessage = logMsg
|
||||
};
|
||||
|
||||
await RecordTaskLog(context, logModel);
|
||||
return logModel;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行指定任务(接收返回结果)
|
||||
/// </summary>
|
||||
/// <param name="context">作业上下文</param>
|
||||
/// <param name="job">业务逻辑方法</param>
|
||||
public async Task<SysTasksLog> ExecuteJob(IJobExecutionContext context, Func<Task<string>> job)
|
||||
{
|
||||
double elapsed = 0;
|
||||
int status = 0;
|
||||
string logMsg;
|
||||
try
|
||||
{
|
||||
//var s = context.Trigger.Key.Name;
|
||||
//记录Job时间
|
||||
Stopwatch stopwatch = new Stopwatch();
|
||||
stopwatch.Start();
|
||||
//执行任,并返回结果
|
||||
string result = await job();
|
||||
stopwatch.Stop();
|
||||
elapsed = stopwatch.Elapsed.TotalMilliseconds;
|
||||
logMsg = result.Length <= 2000 ? result : result.Substring(0, 2000);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
JobExecutionException e2 = new(ex)
|
||||
{
|
||||
//true 是立即重新执行任务
|
||||
RefireImmediately = true
|
||||
};
|
||||
status = 1;
|
||||
logMsg = $"Job Run Fail,Exception:{ex.Message}";
|
||||
WxNoticeHelper.SendMsg("任务执行出错", logMsg);
|
||||
}
|
||||
|
||||
var logModel = new SysTasksLog()
|
||||
{
|
||||
Elapsed = elapsed,
|
||||
Status = status.ToString(),
|
||||
JobMessage = logMsg
|
||||
};
|
||||
|
||||
await RecordTaskLog(context, logModel);
|
||||
return logModel;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 记录到日志
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
/// <param name="logModel"></param>
|
||||
protected async Task RecordTaskLog(IJobExecutionContext context, SysTasksLog logModel)
|
||||
{
|
||||
var tasksLogService = (ISysTasksLogService)App.GetRequiredService(typeof(ISysTasksLogService));
|
||||
var taskQzService = (ISysTasksQzService)App.GetRequiredService(typeof(ISysTasksQzService));
|
||||
|
||||
// 可以直接获取 JobDetail 的值
|
||||
IJobDetail job = context.JobDetail;
|
||||
|
||||
logModel.InvokeTarget = job.JobType.FullName;
|
||||
logModel = await tasksLogService.AddTaskLog(job.Key.Name, logModel);
|
||||
//成功后执行次数+1
|
||||
if (logModel.Status == "0")
|
||||
{
|
||||
await taskQzService.UpdateAsync(f => new SysTasks()
|
||||
{
|
||||
RunTimes = f.RunTimes + 1,
|
||||
LastRunTime = DateTime.Now
|
||||
}, f => f.ID == job.Key.Name);
|
||||
}
|
||||
logger.Info($"执行任务【{job.Key.Name}|{logModel.JobName}】结果={logModel.JobMessage}");
|
||||
}
|
||||
}
|
||||
}
|
||||
59
ZR.Tasks/TaskScheduler/Job_HttpRequest.cs
Normal file
59
ZR.Tasks/TaskScheduler/Job_HttpRequest.cs
Normal file
@@ -0,0 +1,59 @@
|
||||
using Infrastructure;
|
||||
using Infrastructure.Attribute;
|
||||
using Quartz;
|
||||
using Quartz.Impl;
|
||||
using Quartz.Impl.Triggers;
|
||||
using SqlSugar.IOC;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using ZR.Model.System;
|
||||
|
||||
namespace ZR.Tasks.TaskScheduler
|
||||
{
|
||||
/// <summary>
|
||||
/// 定时任务http请求
|
||||
/// </summary>
|
||||
[AppService(ServiceType = typeof(Job_HttpRequest), ServiceLifetime = LifeTime.Scoped)]
|
||||
internal class Job_HttpRequest : JobBase, IJob
|
||||
{
|
||||
//private readonly ISysTasksQzService tasksQzService;
|
||||
private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
|
||||
//public Job_HttpRequest(ISysTasksQzService tasksQzService)
|
||||
//{
|
||||
// this.tasksQzService = tasksQzService;
|
||||
//}
|
||||
public async Task Execute(IJobExecutionContext context)
|
||||
{
|
||||
await ExecuteJob(context, async () => await Run(context));
|
||||
}
|
||||
public async Task Run(IJobExecutionContext context)
|
||||
{
|
||||
AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;
|
||||
//var info = await tasksQzService.CopyNew().GetByIdAsync(trigger.JobName);
|
||||
var info = await DbScoped.SugarScope.CopyNew()
|
||||
.Queryable<SysTasks>()
|
||||
.FirstAsync(f => f.ID == trigger.JobName) ?? throw new CustomException($"任务{trigger?.JobName}网络请求执行失败,任务不存在");
|
||||
string result;
|
||||
if (info.RequestMethod != null && info.RequestMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
result = await HttpHelper.HttpPostAsync(info.ApiUrl, info.JobParams);
|
||||
}
|
||||
else
|
||||
{
|
||||
var url = info.ApiUrl;
|
||||
if (url.IndexOf("?") > -1)
|
||||
{
|
||||
url += "&" + info.JobParams;
|
||||
}
|
||||
else
|
||||
{
|
||||
url += "?" + info.JobParams;
|
||||
}
|
||||
result = await HttpHelper.HttpGetAsync(url);
|
||||
}
|
||||
|
||||
logger.Info($"任务【{info.Name}】网络请求执行结果=" + result);
|
||||
}
|
||||
}
|
||||
}
|
||||
44
ZR.Tasks/TaskScheduler/Job_SqlExecute.cs
Normal file
44
ZR.Tasks/TaskScheduler/Job_SqlExecute.cs
Normal file
@@ -0,0 +1,44 @@
|
||||
using Infrastructure;
|
||||
using Infrastructure.Attribute;
|
||||
using Infrastructure.Extensions;
|
||||
using Quartz;
|
||||
using Quartz.Impl;
|
||||
using Quartz.Impl.Triggers;
|
||||
using SqlSugar.IOC;
|
||||
using System.Threading.Tasks;
|
||||
using ZR.ServiceCore.Services;
|
||||
|
||||
namespace ZR.Tasks.TaskScheduler
|
||||
{
|
||||
[AppService(ServiceType = typeof(Job_SqlExecute), ServiceLifetime = LifeTime.Scoped)]
|
||||
public class Job_SqlExecute : JobBase, IJob
|
||||
{
|
||||
private readonly ISysTasksQzService tasksQzService;
|
||||
private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
|
||||
public Job_SqlExecute(ISysTasksQzService tasksQzService)
|
||||
{
|
||||
this.tasksQzService = tasksQzService;
|
||||
}
|
||||
public async Task Execute(IJobExecutionContext context)
|
||||
{
|
||||
await ExecuteJob(context, async () => await Run(context));
|
||||
}
|
||||
public async Task Run(IJobExecutionContext context)
|
||||
{
|
||||
AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;
|
||||
|
||||
var info = await tasksQzService.GetByIdAsync(trigger.JobName);
|
||||
|
||||
if (info != null && info.SqlText.IsNotEmpty())
|
||||
{
|
||||
var result = DbScoped.SugarScope.Ado.ExecuteCommandWithGo(info.SqlText);
|
||||
logger.Info($"任务【{info.Name}】sql请求执行结果=" + result);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new CustomException($"任务{trigger?.JobName}执行失败,任务不存在");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
39
ZR.Tasks/TaskScheduler/Job_SyncTest.cs
Normal file
39
ZR.Tasks/TaskScheduler/Job_SyncTest.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using Infrastructure.Attribute;
|
||||
using Quartz;
|
||||
using SqlSugar.IOC;
|
||||
using System.Threading.Tasks;
|
||||
using ZR.Model.System;
|
||||
|
||||
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();
|
||||
|
||||
public async Task Execute(IJobExecutionContext context)
|
||||
{
|
||||
await ExecuteJob(context, Run);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 任务使用中注意:所有方法都需要使用异步,并且不能少了await
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public async Task Run()
|
||||
{
|
||||
await Task.Delay(1);
|
||||
//TODO 业务逻辑
|
||||
var db = DbScoped.SugarScope;
|
||||
var info = await db.Queryable<SysDept>().FirstAsync();
|
||||
|
||||
//其他库操作
|
||||
//var db2 = DbScoped.SugarScope.GetConnectionScope(2);
|
||||
System.Console.WriteLine("job test");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user