This commit is contained in:
109
Api/Dilon.Core/Service/Timer/Dto/JobInput.cs
Normal file
109
Api/Dilon.Core/Service/Timer/Dto/JobInput.cs
Normal file
@@ -0,0 +1,109 @@
|
||||
using Furion.DataValidation;
|
||||
using System;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Dilon.Core.Service
|
||||
{
|
||||
/// <summary>
|
||||
/// 任务调度参数
|
||||
/// </summary>
|
||||
public class JobInput : PageInputBase
|
||||
{
|
||||
/// <summary>
|
||||
/// 任务名称
|
||||
/// </summary>
|
||||
/// <example>dilon</example>
|
||||
public string JobName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 任务分组
|
||||
/// </summary>
|
||||
/// <example>dilon</example>
|
||||
public string JobGroup { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开始时间
|
||||
/// </summary>
|
||||
public DateTimeOffset BeginTime { get; set; } = DateTimeOffset.Now;
|
||||
|
||||
/// <summary>
|
||||
/// 结束时间
|
||||
/// </summary>
|
||||
/// <example>null</example>
|
||||
public DateTimeOffset? EndTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Cron表达式
|
||||
/// </summary>
|
||||
/// <example></example>
|
||||
public string Cron { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 执行次数(默认无限循环)
|
||||
/// </summary>
|
||||
/// <example>10</example>
|
||||
public int? RunNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 执行间隔时间,单位秒(如果有Cron,则IntervalSecond失效)
|
||||
/// </summary>
|
||||
/// <example>5</example>
|
||||
public int? Interval { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 触发器类型
|
||||
/// </summary>
|
||||
public TriggerTypeEnum TriggerType { get; set; } = TriggerTypeEnum.Simple;
|
||||
|
||||
/// <summary>
|
||||
/// 请求url
|
||||
/// </summary>
|
||||
public string RequestUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 请求参数(Post,Put请求用)
|
||||
/// </summary>
|
||||
public string RequestParameters { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Headers(可以包含如:Authorization授权认证)
|
||||
/// 格式:{"Authorization":"userpassword.."}
|
||||
/// </summary>
|
||||
public string Headers { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 请求类型
|
||||
/// </summary>
|
||||
/// <example>2</example>
|
||||
public RequestTypeEnum RequestType { get; set; } = RequestTypeEnum.Post;
|
||||
|
||||
/// <summary>
|
||||
/// 描述
|
||||
/// </summary>
|
||||
public string Remark { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 任务状态
|
||||
/// </summary>
|
||||
public string DisplayState { get; set; }
|
||||
}
|
||||
|
||||
public class DeleteJobInput : JobInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 任务Id
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "任务Id不能为空"), DataValidation(ValidationTypes.Numeric)]
|
||||
public long Id { get; set; }
|
||||
}
|
||||
|
||||
public class UpdateJobInput : DeleteJobInput
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public class QueryJobInput : DeleteJobInput
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
96
Api/Dilon.Core/Service/Timer/Dto/JobOutput.cs
Normal file
96
Api/Dilon.Core/Service/Timer/Dto/JobOutput.cs
Normal file
@@ -0,0 +1,96 @@
|
||||
using Quartz;
|
||||
using System;
|
||||
|
||||
namespace Dilon.Core.Service
|
||||
{
|
||||
/// <summary>
|
||||
/// 任务信息---任务详情
|
||||
/// </summary>
|
||||
public class JobOutput
|
||||
{
|
||||
/// <summary>
|
||||
/// 任务名称
|
||||
/// </summary>
|
||||
public string JobName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 任务组名
|
||||
/// </summary>
|
||||
public string JobGroup { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 下次执行时间
|
||||
/// </summary>
|
||||
public DateTime? NextFireTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 上次执行时间
|
||||
/// </summary>
|
||||
public DateTime? PreviousFireTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开始时间
|
||||
/// </summary>
|
||||
public DateTime BeginTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 结束时间
|
||||
/// </summary>
|
||||
public DateTime? EndTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 上次执行的异常信息
|
||||
/// </summary>
|
||||
public string LastErrMsg { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 任务状态
|
||||
/// </summary>
|
||||
public TriggerState TriggerState { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 描述
|
||||
/// </summary>
|
||||
public string Remark { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 显示状态
|
||||
/// </summary>
|
||||
public string DisplayState
|
||||
{
|
||||
get
|
||||
{
|
||||
return TriggerState switch
|
||||
{
|
||||
TriggerState.Normal => "正常",
|
||||
TriggerState.Paused => "暂停",
|
||||
TriggerState.Complete => "完成",
|
||||
TriggerState.Error => "异常",
|
||||
TriggerState.Blocked => "阻塞",
|
||||
TriggerState.None => "不存在",
|
||||
_ => "未知",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 时间间隔
|
||||
/// </summary>
|
||||
public string Interval { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 请求地址
|
||||
/// </summary>
|
||||
public string RequestUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 请求类型
|
||||
/// </summary>
|
||||
public string RequestType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 已经执行的次数
|
||||
/// </summary>
|
||||
public string RunNumber { get; set; }
|
||||
}
|
||||
}
|
||||
68
Api/Dilon.Core/Service/Timer/HttpJob.cs
Normal file
68
Api/Dilon.Core/Service/Timer/HttpJob.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
using Furion.JsonSerialization;
|
||||
using Furion.RemoteRequest.Extensions;
|
||||
using Quartz;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Dilon.Core.Service
|
||||
{
|
||||
[DisallowConcurrentExecution]
|
||||
public class HttpJob : IJob
|
||||
{
|
||||
//protected readonly int _maxLogCount = 20; //最多保存日志数量
|
||||
//protected Stopwatch _stopwatch = new();
|
||||
|
||||
public async Task Execute(IJobExecutionContext context)
|
||||
{
|
||||
// 获取相关参数
|
||||
var requestUrl = context.JobDetail.JobDataMap.GetString(SchedulerDef.REQUESTURL)?.Trim();
|
||||
requestUrl = requestUrl?.IndexOf("http") == 0 ? requestUrl : "http://" + requestUrl;
|
||||
var requestParameters = context.JobDetail.JobDataMap.GetString(SchedulerDef.REQUESTPARAMETERS);
|
||||
var headersString = context.JobDetail.JobDataMap.GetString(SchedulerDef.HEADERS);
|
||||
var headers = !string.IsNullOrWhiteSpace(headersString) ? JSON.GetJsonSerializer().Deserialize<Dictionary<string, string>>(headersString.Trim()) : null;
|
||||
var requestType = (RequestTypeEnum)int.Parse(context.JobDetail.JobDataMap.GetString(SchedulerDef.REQUESTTYPE));
|
||||
|
||||
// var response = new HttpResponseMessage();
|
||||
switch (requestType)
|
||||
{
|
||||
case RequestTypeEnum.Get:
|
||||
await requestUrl.SetHeaders(headers).GetAsync();
|
||||
break;
|
||||
case RequestTypeEnum.Post:
|
||||
await requestUrl.SetHeaders(headers).SetQueries(requestParameters).PostAsync();
|
||||
break;
|
||||
case RequestTypeEnum.Put:
|
||||
await requestUrl.SetHeaders(headers).SetQueries(requestParameters).PutAsync();
|
||||
break;
|
||||
case RequestTypeEnum.Delete:
|
||||
await requestUrl.SetHeaders(headers).DeleteAsync();
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
//_stopwatch.Restart(); // 开始监视代码运行时间
|
||||
//// var beginTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
//Debug.WriteLine(DateTimeOffset.Now.ToString());
|
||||
|
||||
//// var endTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
//_stopwatch.Stop(); // 停止监视
|
||||
|
||||
////// 执行次数
|
||||
////var runNumber = context.JobDetail.JobDataMap.GetString(SchedulerDef.RUNNUMBER);
|
||||
////context.JobDetail.JobDataMap[SchedulerDef.RUNNUMBER] = runNumber;
|
||||
|
||||
//// 耗时
|
||||
//var seconds = _stopwatch.Elapsed.TotalSeconds; // 总秒数
|
||||
//var executeTime = seconds >= 1 ? seconds + "秒" : _stopwatch.Elapsed.TotalMilliseconds + "毫秒";
|
||||
|
||||
////// 只保留20条记录
|
||||
////var logs = context.JobDetail.JobDataMap[SchedulerDef.LOGLIST] as List<string> ?? new List<string>();
|
||||
////if (logs.Count >= _maxLogCount)
|
||||
//// logs.RemoveRange(0, logs.Count - _maxLogCount);
|
||||
|
||||
////logs.Add($"<p class='msgList'><span class='time'>{beginTime} 至 {endTime} 【耗时】{executeTime}</span></p>");
|
||||
////context.JobDetail.JobDataMap[SchedulerDef.LOGLIST] = logs;
|
||||
}
|
||||
}
|
||||
}
|
||||
16
Api/Dilon.Core/Service/Timer/ISysTimerService.cs
Normal file
16
Api/Dilon.Core/Service/Timer/ISysTimerService.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Dilon.Core.Service
|
||||
{
|
||||
public interface ISysTimerService
|
||||
{
|
||||
Task AddJob(JobInput input);
|
||||
Task DeleteJob(DeleteJobInput input);
|
||||
Task<dynamic> GetJobPageList([FromQuery] JobInput input);
|
||||
Task<dynamic> GetTimer([FromQuery] QueryJobInput input);
|
||||
Task StopScheduleJobAsync(JobInput input);
|
||||
Task TriggerJobAsync(JobInput input);
|
||||
Task UpdateJob(UpdateJobInput input);
|
||||
}
|
||||
}
|
||||
336
Api/Dilon.Core/Service/Timer/SchedulerCenter.cs
Normal file
336
Api/Dilon.Core/Service/Timer/SchedulerCenter.cs
Normal file
@@ -0,0 +1,336 @@
|
||||
using Furion.DatabaseAccessor;
|
||||
using Furion.DependencyInjection;
|
||||
using Furion.FriendlyException;
|
||||
using Mapster;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Quartz;
|
||||
using Quartz.Impl;
|
||||
using Quartz.Impl.Matchers;
|
||||
using Quartz.Impl.Triggers;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Dilon.Core.Service
|
||||
{
|
||||
/// <summary>
|
||||
/// 任务调度中心
|
||||
/// </summary>
|
||||
public class SchedulerCenter : ISingleton
|
||||
{
|
||||
private IScheduler _scheduler = null;
|
||||
|
||||
public SchedulerCenter()
|
||||
{
|
||||
_ = StartScheduleAsync();
|
||||
|
||||
InitAllJob().GetAwaiter();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 开启调度器
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private async Task<bool> StartScheduleAsync()
|
||||
{
|
||||
if (_scheduler == null)
|
||||
{
|
||||
// 初始化Scheduler
|
||||
var schedulerFactory = new StdSchedulerFactory();
|
||||
_scheduler = await schedulerFactory.GetScheduler();
|
||||
|
||||
// 开启调度器
|
||||
if (_scheduler.InStandbyMode)
|
||||
await _scheduler.Start();
|
||||
}
|
||||
return _scheduler.InStandbyMode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 停止调度器
|
||||
/// </summary>
|
||||
private async Task<bool> StopScheduleAsync()
|
||||
{
|
||||
//判断调度是否已经关闭
|
||||
if (!_scheduler.InStandbyMode)
|
||||
{
|
||||
//等待任务运行完成
|
||||
await _scheduler.Standby(); // 注意:Shutdown后Start会报错,所以这里使用暂停。
|
||||
}
|
||||
return !_scheduler.InStandbyMode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加一个工作任务
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<dynamic> AddScheduleJobAsync(JobInput input)
|
||||
{
|
||||
// 检查任务是否已存在
|
||||
var jobKey = new JobKey(input.JobName, input.JobGroup);
|
||||
if (await _scheduler.CheckExists(jobKey))
|
||||
throw Oops.Oh("任务已存在");
|
||||
|
||||
// http请求配置
|
||||
var httpDir = new Dictionary<string, string>()
|
||||
{
|
||||
{ SchedulerDef.ENDAT, input.EndTime.ToString()},
|
||||
{ SchedulerDef.REQUESTURL, input.RequestUrl},
|
||||
{ SchedulerDef.HEADERS, input.Headers },
|
||||
{ SchedulerDef.REQUESTPARAMETERS, input.RequestParameters},
|
||||
{ SchedulerDef.REQUESTTYPE, ((int)input.RequestType).ToString()},
|
||||
{ SchedulerDef.RUNNUMBER, input.RunNumber.ToString()}
|
||||
};
|
||||
|
||||
// 定义这个工作,并将其绑定到我们的IJob实现类
|
||||
IJobDetail job = JobBuilder.Create<HttpJob>()
|
||||
.SetJobData(new JobDataMap(httpDir))
|
||||
.WithDescription(input.Remark)
|
||||
.WithIdentity(input.JobName, input.JobGroup)
|
||||
.Build();
|
||||
// 创建触发器
|
||||
ITrigger trigger = input.TriggerType == TriggerTypeEnum.Cron // && CronExpression.IsValidExpression(entity.Cron)
|
||||
? CreateCronTrigger(input)
|
||||
: CreateSimpleTrigger(input);
|
||||
|
||||
return await _scheduler.ScheduleJob(job, trigger);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 暂停任务
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
public async Task StopScheduleJobAsync(JobInput input)
|
||||
{
|
||||
var jobKey = new JobKey(input.JobName, input.JobGroup);
|
||||
await _scheduler.PauseJob(jobKey);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除任务
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
public async Task DeleteScheduleJobAsync(DeleteJobInput input)
|
||||
{
|
||||
var jobKey = new JobKey(input.JobName, input.JobGroup);
|
||||
await _scheduler.PauseJob(jobKey);
|
||||
await _scheduler.DeleteJob(jobKey);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 恢复运行暂停的任务
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("/sysTimer/resumeJob")]
|
||||
public async Task<dynamic> ResumeJobAsync(JobInput input)
|
||||
{
|
||||
//检查任务是否存在
|
||||
var jobKey = new JobKey(input.JobName, input.JobGroup);
|
||||
if (await _scheduler.CheckExists(jobKey))
|
||||
{
|
||||
var jobDetail = await _scheduler.GetJobDetail(jobKey);
|
||||
var endTime = jobDetail.JobDataMap.GetString(SchedulerDef.ENDAT);
|
||||
if (!string.IsNullOrWhiteSpace(endTime) && DateTime.Parse(endTime) <= DateTime.Now)
|
||||
{
|
||||
throw Oops.Oh("Job的结束时间已过期");
|
||||
}
|
||||
else
|
||||
{
|
||||
await _scheduler.ResumeJob(jobKey); // 任务已经存在则暂停任务
|
||||
}
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询任务
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<JobInput> QueryJobAsync(JobInput input)
|
||||
{
|
||||
var jobKey = new JobKey(input.JobName, input.JobGroup);
|
||||
var jobDetail = await _scheduler.GetJobDetail(jobKey);
|
||||
var triggersList = await _scheduler.GetTriggersOfJob(jobKey);
|
||||
var triggers = triggersList.AsEnumerable().FirstOrDefault();
|
||||
var intervalSeconds = (triggers as SimpleTriggerImpl)?.RepeatInterval.TotalSeconds;
|
||||
var endTime = jobDetail.JobDataMap.GetString(SchedulerDef.ENDAT);
|
||||
return new JobInput
|
||||
{
|
||||
BeginTime = triggers.StartTimeUtc.LocalDateTime,
|
||||
EndTime = !string.IsNullOrWhiteSpace(endTime) ? DateTime.Parse(endTime) : null,
|
||||
Interval = intervalSeconds.HasValue ? Convert.ToInt32(intervalSeconds.Value) : null,
|
||||
JobGroup = input.JobGroup,
|
||||
JobName = input.JobName,
|
||||
Cron = (triggers as CronTriggerImpl)?.CronExpressionString,
|
||||
RunNumber = (triggers as SimpleTriggerImpl)?.RepeatCount,
|
||||
TriggerType = triggers is SimpleTriggerImpl ? TriggerTypeEnum.Simple : TriggerTypeEnum.Cron,
|
||||
Remark = jobDetail.Description,
|
||||
RequestUrl = jobDetail.JobDataMap.GetString(SchedulerDef.REQUESTURL),
|
||||
RequestType = (RequestTypeEnum)int.Parse(jobDetail.JobDataMap.GetString(SchedulerDef.REQUESTTYPE)),
|
||||
RequestParameters = jobDetail.JobDataMap.GetString(SchedulerDef.REQUESTPARAMETERS),
|
||||
Headers = jobDetail.JobDataMap.GetString(SchedulerDef.HEADERS)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 立即执行
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
public async Task TriggerJobAsync(JobInput input)
|
||||
{
|
||||
var jobKey = new JobKey(input.JobName, input.JobGroup);
|
||||
await _scheduler.ResumeJob(jobKey);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取任务日志
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<List<string>> GetJobLogsAsync(JobInput input)
|
||||
{
|
||||
var jobKey = new JobKey(input.JobName, input.JobGroup);
|
||||
var jobDetail = await _scheduler.GetJobDetail(jobKey);
|
||||
return jobDetail.JobDataMap[SchedulerDef.LOGLIST] as List<string>;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取任务运行次数
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<long> GetRunNumberAsync(JobInput input)
|
||||
{
|
||||
var jobKey = new JobKey(input.JobName, input.JobGroup);
|
||||
var jobDetail = await _scheduler.GetJobDetail(jobKey);
|
||||
return jobDetail.JobDataMap.GetLong(SchedulerDef.RUNNUMBER);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取所有任务详情
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public async Task<List<JobOutput>> GetJobList()
|
||||
{
|
||||
var jobInfoList = new List<JobOutput>();
|
||||
var groupNames = await _scheduler.GetJobGroupNames();
|
||||
var jboKeyList = new List<JobKey>();
|
||||
foreach (var groupName in groupNames.OrderBy(t => t))
|
||||
{
|
||||
jboKeyList.AddRange(await _scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(groupName)));
|
||||
//jobInfoList.Add(new JobOutput() { JobGroup = groupName });
|
||||
}
|
||||
foreach (var jobKey in jboKeyList.OrderBy(t => t.Name))
|
||||
{
|
||||
var jobDetail = await _scheduler.GetJobDetail(jobKey);
|
||||
var triggersList = await _scheduler.GetTriggersOfJob(jobKey);
|
||||
var triggers = triggersList.AsEnumerable().FirstOrDefault();
|
||||
|
||||
var interval = triggers is SimpleTriggerImpl
|
||||
? ((triggers as SimpleTriggerImpl)?.RepeatInterval.ToString())
|
||||
: ((triggers as CronTriggerImpl)?.CronExpressionString);
|
||||
|
||||
jobInfoList.Add(new JobOutput
|
||||
{
|
||||
JobName = jobKey.Name,
|
||||
JobGroup = jobKey.Group,
|
||||
LastErrMsg = jobDetail.JobDataMap.GetString(SchedulerDef.EXCEPTION),
|
||||
RequestUrl = jobDetail.JobDataMap.GetString(SchedulerDef.REQUESTURL),
|
||||
TriggerState = await _scheduler.GetTriggerState(triggers.Key),
|
||||
PreviousFireTime = triggers.GetPreviousFireTimeUtc()?.LocalDateTime,
|
||||
NextFireTime = triggers.GetNextFireTimeUtc()?.LocalDateTime,
|
||||
BeginTime = triggers.StartTimeUtc.LocalDateTime,
|
||||
Interval = interval,
|
||||
EndTime = triggers.EndTimeUtc?.LocalDateTime,
|
||||
Remark = jobDetail.Description,
|
||||
RequestType = jobDetail.JobDataMap.GetString(SchedulerDef.REQUESTTYPE),
|
||||
RunNumber = jobDetail.JobDataMap.GetString(SchedulerDef.RUNNUMBER)
|
||||
});
|
||||
}
|
||||
return jobInfoList;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从数据库里面获取所有任务并初始化
|
||||
/// </summary>
|
||||
private async Task InitAllJob()
|
||||
{
|
||||
var jobList = Db.GetRepository<SysTimer>().DetachedEntities.Select(u => u.Adapt<JobInput>()).ToList();
|
||||
var jobTasks = new List<Task<dynamic>>();
|
||||
jobList.ForEach(u =>
|
||||
{
|
||||
jobTasks.Add(AddScheduleJobAsync(u));
|
||||
});
|
||||
await Task.WhenAll(jobTasks);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建类型Simple的触发器
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
private static ITrigger CreateSimpleTrigger(JobInput input)
|
||||
{
|
||||
//作业触发器
|
||||
if (input.RunNumber.HasValue && input.RunNumber > 0)
|
||||
{
|
||||
return TriggerBuilder.Create()
|
||||
.WithIdentity(input.JobName, input.JobGroup)
|
||||
.StartAt(input.BeginTime)//开始时间
|
||||
//.EndAt(entity.EndTime)//结束数据
|
||||
.WithSimpleSchedule(x =>
|
||||
{
|
||||
x.WithIntervalInSeconds(input.Interval.Value)//执行时间间隔,单位秒
|
||||
.WithRepeatCount(input.RunNumber.Value)//执行次数、默认从0开始
|
||||
.WithMisfireHandlingInstructionFireNow();
|
||||
})
|
||||
.ForJob(input.JobName, input.JobGroup)//作业名称
|
||||
.Build();
|
||||
}
|
||||
else
|
||||
{
|
||||
return TriggerBuilder.Create()
|
||||
.WithIdentity(input.JobName, input.JobGroup)
|
||||
.StartAt(input.BeginTime)//开始时间
|
||||
//.EndAt(entity.EndTime)//结束数据
|
||||
.WithSimpleSchedule(x =>
|
||||
{
|
||||
x.WithIntervalInSeconds(input.Interval.Value)//执行时间间隔,单位秒
|
||||
.RepeatForever()//无限循环
|
||||
.WithMisfireHandlingInstructionFireNow();
|
||||
})
|
||||
.ForJob(input.JobName, input.JobGroup)//作业名称
|
||||
.Build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建类型Cron的触发器
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
private static ITrigger CreateCronTrigger(JobInput input)
|
||||
{
|
||||
if (!CronExpression.IsValidExpression(input.Cron))
|
||||
throw Oops.Oh("Cron表达式错误");
|
||||
|
||||
// 作业触发器
|
||||
return TriggerBuilder.Create()
|
||||
|
||||
.WithIdentity(input.JobName, input.JobGroup)
|
||||
.StartAt(input.BeginTime) //开始时间
|
||||
//.EndAt(entity.EndTime) //结束时间
|
||||
.WithCronSchedule(input.Cron, cronScheduleBuilder => cronScheduleBuilder.WithMisfireHandlingInstructionFireAndProceed())//指定cron表达式
|
||||
.ForJob(input.JobName, input.JobGroup)//作业名称
|
||||
.Build();
|
||||
}
|
||||
}
|
||||
}
|
||||
63
Api/Dilon.Core/Service/Timer/SchedulerDef.cs
Normal file
63
Api/Dilon.Core/Service/Timer/SchedulerDef.cs
Normal file
@@ -0,0 +1,63 @@
|
||||
namespace Dilon.Core.Service
|
||||
{
|
||||
/// <summary>
|
||||
/// 任务调度相关常量
|
||||
/// </summary>
|
||||
public class SchedulerDef
|
||||
{
|
||||
/// <summary>
|
||||
/// 请求url RequestUrl
|
||||
/// </summary>
|
||||
public const string REQUESTURL = "RequestUrl";
|
||||
/// <summary>
|
||||
/// 请求参数 RequestParameters
|
||||
/// </summary>
|
||||
public const string REQUESTPARAMETERS = "RequestParameters";
|
||||
/// <summary>
|
||||
/// Headers(可以包含:Authorization授权认证)
|
||||
/// </summary>
|
||||
public const string HEADERS = "Headers";
|
||||
/// <summary>
|
||||
/// 请求类型 RequestType
|
||||
/// </summary>
|
||||
public const string REQUESTTYPE = "RequestType";
|
||||
/// <summary>
|
||||
/// 日志 LogList
|
||||
/// </summary>
|
||||
public const string LOGLIST = "LogList";
|
||||
/// <summary>
|
||||
/// 异常 Exception
|
||||
/// </summary>
|
||||
public const string EXCEPTION = "Exception";
|
||||
/// <summary>
|
||||
/// 执行次数
|
||||
/// </summary>
|
||||
public const string RUNNUMBER = "RunNumber";
|
||||
/// <summary>
|
||||
/// 任务结束时间
|
||||
/// </summary>
|
||||
public const string ENDAT = "EndAt";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// http请求类型
|
||||
/// </summary>
|
||||
public enum RequestTypeEnum
|
||||
{
|
||||
None = 0,
|
||||
Get = 1,
|
||||
Post = 2,
|
||||
Put = 3,
|
||||
Delete = 4
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 触发器类型
|
||||
/// </summary>
|
||||
public enum TriggerTypeEnum
|
||||
{
|
||||
None = 0,
|
||||
Simple = 1,
|
||||
Cron = 2
|
||||
}
|
||||
}
|
||||
145
Api/Dilon.Core/Service/Timer/SysTimerService.cs
Normal file
145
Api/Dilon.Core/Service/Timer/SysTimerService.cs
Normal file
@@ -0,0 +1,145 @@
|
||||
using Furion.DatabaseAccessor;
|
||||
using Furion.DatabaseAccessor.Extensions;
|
||||
using Furion.DependencyInjection;
|
||||
using Furion.DynamicApiController;
|
||||
using Furion.FriendlyException;
|
||||
using Mapster;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Dilon.Core.Service
|
||||
{
|
||||
/// <summary>
|
||||
/// 任务调度服务
|
||||
/// </summary>
|
||||
[ApiDescriptionSettings(Name = "Timer", Order = 100)]
|
||||
public class SysTimerService : ISysTimerService, IDynamicApiController, IScoped
|
||||
{
|
||||
private readonly IRepository<SysTimer> _sysTimerRep; // 任务表仓储
|
||||
private readonly SchedulerCenter _schedulerCenter;
|
||||
|
||||
public SysTimerService(IRepository<SysTimer> sysTimerRep, SchedulerCenter schedulerCenter)
|
||||
{
|
||||
_sysTimerRep = sysTimerRep;
|
||||
_schedulerCenter = schedulerCenter;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 分页获取任务列表
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("/sysTimers/page")]
|
||||
public async Task<dynamic> GetJobPageList([FromQuery] JobInput input)
|
||||
{
|
||||
var jobList = await _schedulerCenter.GetJobList();
|
||||
|
||||
var jobName = !string.IsNullOrEmpty(input.JobName?.Trim());
|
||||
var timers = await _sysTimerRep.DetachedEntities
|
||||
.Where((jobName, u => EF.Functions.Like(u.JobName, $"%{input.JobName.Trim()}%")))
|
||||
.Select(u => u.Adapt<JobInput>())
|
||||
.ToPagedListAsync(input.PageNo, input.PageSize);
|
||||
|
||||
timers.Items.ToList().ForEach(u =>
|
||||
{
|
||||
u.DisplayState = jobList.Find(m => m.JobName == u.JobName)?.DisplayState;
|
||||
});
|
||||
return XnPageResult<JobInput>.PageResult(timers);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 增加任务
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("/sysTimers/add")]
|
||||
public async Task AddJob(JobInput input)
|
||||
{
|
||||
var isExist = await _sysTimerRep.AnyAsync(u => u.JobName == input.JobName, false);
|
||||
if (isExist)
|
||||
throw Oops.Oh(ErrorCode.D1100);
|
||||
|
||||
var timer = input.Adapt<SysTimer>();
|
||||
await _sysTimerRep.InsertAsync(timer);
|
||||
|
||||
// 添加到调度
|
||||
await _schedulerCenter.AddScheduleJobAsync(input);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除任务
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("/sysTimers/delete")]
|
||||
public async Task DeleteJob(DeleteJobInput input)
|
||||
{
|
||||
var timer = await _sysTimerRep.FirstOrDefaultAsync(u => u.Id == input.Id);
|
||||
if (timer == null)
|
||||
throw Oops.Oh(ErrorCode.D1101);
|
||||
|
||||
await timer.DeleteAsync();
|
||||
|
||||
// 从调度器里删除
|
||||
await _schedulerCenter.DeleteScheduleJobAsync(input);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 修改任务
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("/sysTimers/edit")]
|
||||
public async Task UpdateJob(UpdateJobInput input)
|
||||
{
|
||||
// 排除自己并且判断与其他是否相同
|
||||
var isExist = await _sysTimerRep.AnyAsync(u => u.JobName == input.JobName && u.Id != input.Id, false);
|
||||
if (isExist) throw Oops.Oh(ErrorCode.D1100);
|
||||
|
||||
var timer = input.Adapt<SysTimer>();
|
||||
await timer.UpdateAsync(ignoreNullValues: true);
|
||||
|
||||
// 先从调度器里删除
|
||||
var oldTimer = await _sysTimerRep.FirstOrDefaultAsync(u => u.Id == input.Id, false);
|
||||
await _schedulerCenter.DeleteScheduleJobAsync(oldTimer.Adapt<DeleteJobInput>());
|
||||
|
||||
// 再加到调度里
|
||||
await _schedulerCenter.AddScheduleJobAsync(timer.Adapt<JobInput>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查看任务
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("/sysTimers/detail")]
|
||||
public async Task<dynamic> GetTimer([FromQuery] QueryJobInput input)
|
||||
{
|
||||
return await _sysTimerRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 停止任务
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("/sysTimers/stop")]
|
||||
public async Task StopScheduleJobAsync(JobInput input)
|
||||
{
|
||||
await _schedulerCenter.StopScheduleJobAsync(input);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 启动任务
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("/sysTimers/start")]
|
||||
public async Task TriggerJobAsync(JobInput input)
|
||||
{
|
||||
await _schedulerCenter.TriggerJobAsync(input);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user