using Quartz;
|
using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
using System.Text;
|
using System.Threading.Tasks;
|
|
namespace IStation.Server
|
{
|
/// <summary>
|
/// 自定义计划重复任务
|
/// </summary>
|
public class CustomCronRepeatJob : Quartz.IJob
|
{
|
//自定义计划任务字典
|
private static Dictionary<long,CustomCronJobHelper> _dict=new Dictionary<long, CustomCronJobHelper>();
|
|
/// <summary>
|
/// 任务id
|
/// </summary>
|
public long JobID { get; set; }
|
|
/// <summary>
|
///
|
/// </summary>
|
public Task Execute(IJobExecutionContext context)
|
{
|
return Task.Run(async () =>
|
{
|
try
|
{
|
//获取任务
|
var model = new Service.CustomCronJob().GetByID(JobID);
|
|
//获取任务失败后,停止任务并移除任务辅助类
|
if (model == null)
|
{
|
if (_dict.ContainsKey(JobID))
|
{
|
await _dict[JobID].CancelJob();
|
_dict.Remove(JobID);
|
}
|
return;
|
}
|
|
//尚未创建计划任务时,创建计划任务辅助类
|
if (!_dict.ContainsKey(JobID))
|
{
|
var jobHelper = new CustomCronJobHelper();
|
await jobHelper.StartJob(model);
|
_dict.Add(JobID, jobHelper);
|
return;
|
}
|
|
//任务已存在,检查任务执行间隔是否发生变化,若发生变化,重置任务
|
if (_dict[JobID].Instance.Expression != model.Expression)
|
{
|
await _dict[JobID].CancelJob();
|
var jobHelper = new CustomCronJobHelper();
|
await jobHelper.StartJob(model);
|
_dict[JobID] = jobHelper;
|
}
|
|
}
|
catch (Exception ex)
|
{
|
LogHelper.Error("自定义计划重复任务,执行出错", ex);
|
var e = new JobExecutionException(ex);
|
throw e;
|
}
|
});
|
|
|
}
|
|
/// <summary>
|
/// 取消任务
|
/// </summary>
|
/// <returns></returns>
|
public async Task CancelJob()
|
{
|
await CancelJob(JobID);
|
}
|
|
/// <summary>
|
/// 取消任务
|
/// </summary>
|
/// <param name="jobId">任务id</param>
|
public static async Task CancelJob(long jobId)
|
{
|
if (_dict.ContainsKey(jobId))
|
{
|
await _dict[jobId].CancelJob();
|
_dict.Remove(jobId);
|
}
|
|
}
|
|
/// <summary>
|
/// 取下任务
|
/// </summary>
|
public static async Task CancelJobs()
|
{
|
foreach (var key in _dict.Keys)
|
{
|
await CancelJob(key);
|
}
|
}
|
|
}
|
|
}
|