public class QuartzHelper
{
private IScheduler scheduler;
private List<JobInfo> jobInfos;
private string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "jobs.json");
/// <summary>
/// 構(gòu)造函數(shù),初始化定時(shí)任務(wù)管理器
/// </summary>
public QuartzHelper()
{
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
scheduler = schedulerFactory.GetScheduler().Result;
scheduler.Start().Wait();
LoadJobInfosApi().Wait();
}
/// <summary>
/// 保存作業(yè)信息到本地 JSON 文件
/// </summary>
private void SaveJobInfos()
{
string json = JsonConvert.SerializeObject(jobInfos);
File.WriteAllText(filePath, json);
}
/// <summary>
/// 加載本地 JSON 文件中的作業(yè)信息
/// </summary>
private async Task LoadJobInfosApi()
{
if (File.Exists(filePath))
{
string json = File.ReadAllText(filePath);
jobInfos = JsonConvert.DeserializeObject<List<JobInfo>>(json) ?? new List<JobInfo>();
foreach (var jobInfo in jobInfos)
{
// 創(chuàng)建委托的唯一鍵
var delegateKey = Guid.NewGuid().ToString();
// 將委托存儲(chǔ)在靜態(tài)字典中
HttpJob.Delegates[delegateKey] = jobInfo.HttpJob;
// 創(chuàng)建并調(diào)度作業(yè)
IJobDetail job = JobBuilder.Create<HttpJob>()
.WithIdentity(jobInfo.JobName, jobInfo.GroupName).UsingJobData("delegateKey", delegateKey) // 將委托的鍵添加到JobDataMap
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity(jobInfo.JobName, jobInfo.GroupName)
.WithCronSchedule(jobInfo.CronExpression)
//.StartNow()
.Build();
await scheduler.ScheduleJob(job, trigger);
// 根據(jù)任務(wù)狀態(tài)恢復(fù)或暫停任務(wù)
if (jobInfo.Status == JobStatus.正常運(yùn)行)
{
await ResumeJob(jobInfo.JobName, jobInfo.GroupName);
}
else
{
await PauseJob(jobInfo.JobName, jobInfo.GroupName);
}
}
}
else
{
jobInfos = new List<JobInfo>();
}
}
#region 執(zhí)行普通任務(wù)時(shí)使用,傳委托時(shí)可以參考此方法
///// <summary>
///// 新建任務(wù)并立即執(zhí)行
///// </summary>
//[Obsolete("執(zhí)行普通任務(wù)時(shí)使用,可以傳委托使用")]
//public async Task AddJob(string jobName, string groupName, string cronExpression, Func<bool> func, string description = "")
//{
// if (jobInfos.Any(c => c.JobName == jobName && c.GroupName == groupName))
// {
// return;
// }
// // 創(chuàng)建委托的唯一鍵
// var delegateKey = Guid.NewGuid().ToString();
// // 將委托存儲(chǔ)在靜態(tài)字典中
// // MyJobClass.Delegates[delegateKey] = func;
// // 創(chuàng)建作業(yè)信息并保存到列表 需要將func 加入到j(luò)obInfo 中做作業(yè)持久化!!!!
// var jobInfo = new JobInfo { JobName = jobName, GroupName = groupName, CronExpression = cronExpression, Status = JobStatus.正常運(yùn)行, Description = description, JobCreateTime = DateTime.Now };
// jobInfos.Add(jobInfo);
// SaveJobInfos();
// // 創(chuàng)建Quartz作業(yè)和觸發(fā)器
// IJobDetail job = JobBuilder.Create<MyJobClass>()
// .WithIdentity(jobName, groupName)
// .UsingJobData("delegateKey", delegateKey) // 將委托的鍵添加到JobDataMap
// .Build();
// ITrigger trigger = TriggerBuilder.Create()
// .WithIdentity(jobName + "Trigger", groupName)
// .StartNow()
// .WithCronSchedule(cronExpression).WithDescription(description)
// .Build();
// await scheduler.ScheduleJob(job, trigger);
//}
#endregion
/// <summary>
/// 新建任務(wù)并立即執(zhí)行
/// </summary>
public async Task AddJobApi(string jobName, string groupName, string cronExpression, HttpJobInfo httpJobInfo, string description = "")
{
if (jobInfos.Any(c => c.JobName == jobName && c.GroupName == groupName))
{
return;
}
// 創(chuàng)建委托的唯一鍵
var delegateKey = Guid.NewGuid().ToString();
// 將委托存儲(chǔ)在靜態(tài)字典中
HttpJob.Delegates[delegateKey] = httpJobInfo;
// 創(chuàng)建作業(yè)信息并保存到列表 需要將func 加入到j(luò)obInfo 中做作業(yè)持久化!!!!
var jobInfo = new JobInfo { JobName = jobName, GroupName = groupName, CronExpression = cronExpression, HttpJob = httpJobInfo, Status = JobStatus.正常運(yùn)行, Description = description, JobCreateTime = DateTime.Now };
jobInfos.Add(jobInfo);
SaveJobInfos();
// 創(chuàng)建Quartz作業(yè)和觸發(fā)器
IJobDetail job = JobBuilder.Create<HttpJob>()
.WithIdentity(jobName, groupName)
.UsingJobData("delegateKey", delegateKey) // 將委托的鍵添加到JobDataMap
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity(jobName + "Trigger", groupName)
.StartNow()
.WithCronSchedule(cronExpression).WithDescription(description)
.Build();
await scheduler.ScheduleJob(job, trigger);
}
/// <summary>
/// 暫停任務(wù)
/// </summary>
public async Task PauseJob(string jobName, string groupName)
{
await scheduler.PauseJob(new JobKey(jobName, groupName));
var job = jobInfos.FirstOrDefault(j => j.JobName == jobName && j.GroupName == groupName);
if (job != null)
{
job.Status = JobStatus.暫停;
SaveJobInfos();
}
}
/// <summary>
/// 開(kāi)啟任務(wù)
/// </summary>
public async Task ResumeJob(string jobName, string groupName)
{
await scheduler.ResumeJob(new JobKey(jobName, groupName));
var job = jobInfos.FirstOrDefault(j => j.JobName == jobName && j.GroupName == groupName);
if (job != null)
{
job.Status = JobStatus.正常運(yùn)行;
SaveJobInfos();
}
}
/// <summary>
/// 立即執(zhí)行任務(wù)
/// </summary>
public async Task TriggerJob(string jobName, string groupName)
{
await scheduler.TriggerJob(new JobKey(jobName, groupName));
var job = jobInfos.FirstOrDefault(j => j.JobName == jobName && j.GroupName == groupName);
if (job != null)
{
job.LastExecutionTime = DateTime.Now;
SaveJobInfos();
}
}
/// <summary>
/// 修改任務(wù)
/// </summary>
public async Task ModifyJob(string jobName, string groupName, string cronExpression, HttpJobInfo httpJobInfo, string description = "")
{
await DeleteJob(jobName, groupName);
await AddJobApi(jobName, groupName, cronExpression, httpJobInfo, description);
}
/// <summary>
/// 刪除任務(wù)
/// </summary>
public async Task DeleteJob(string jobName, string groupName)
{
await scheduler.DeleteJob(new JobKey(jobName, groupName));
jobInfos.RemoveAll(j => j.JobName == jobName && j.GroupName == groupName);
SaveJobInfos();
}
/// <summary>
/// 獲取當(dāng)前所有任務(wù)列表
/// </summary>
public List<JobInfo> GetAllJobs()
{
if (File.Exists(filePath))
{
string json = File.ReadAllText(filePath);
jobInfos = JsonConvert.DeserializeObject<List<JobInfo>>(json) ?? new List<JobInfo>();
return jobInfos;
}
else
return null;
}
}
QuartzHelper