JXMovies/Core/JXCMS.Core/TimingTask/QuartzTask.cs
2020-02-16 22:11:24 +08:00

93 lines
2.9 KiB
C#

using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Quartz;
using Quartz.Impl;
namespace JXCMS.Core.TimingTask
{
public class QuartzTask
{
private ISchedulerFactory _schedulerFactory;
private IScheduler _scheduler;
private QuartzTask()
{
_schedulerFactory = new StdSchedulerFactory();
_scheduler = _schedulerFactory.GetScheduler().Result;
_scheduler.Start();
}
private static QuartzTask _instance;
public static QuartzTask Instance()
{
if (_instance == null)
{
_instance = new QuartzTask();
}
return _instance;
}
public async Task<bool> AddTask(Type jobType, string cron, string jobName, string jobGroup = "default", params (string name, object value)[] param)
{
var time = DateTime.Now;
var job = JobBuilder.Create(jobType).WithIdentity(jobName, jobGroup).Build();
var trigger = TriggerBuilder.Create().WithIdentity(jobName + "trigger").StartNow().WithCronSchedule(cron).Build();
foreach (var par in param)
{
job.JobDataMap.Put(par.name, par.value);
}
var offset = await _scheduler.ScheduleJob(job, trigger);
return true;
}
public async Task<bool> DeleteTask(string jobName, string jobGroup = "default")
{
return await _scheduler.DeleteJob(new JobKey(jobName, jobGroup));
}
public async Task<bool> DeleteTasks(ReadOnlyCollection<JobKey> jobKeys)
{
return await _scheduler.DeleteJobs(jobKeys);
}
/// <summary>
/// Corn表达式的运行时间
/// </summary>
/// <param name="cron">表达式</param>
/// <param name="times">计算次数</param>
/// <param name="startTime">开始时间</param>
/// <returns></returns>
public static string GetCronSchedule(String cron, int times, DateTimeOffset startTime)
{
String timeSchedule = "";
if (!CronExpression.IsValidExpression(cron))
{
return "Cron表达式不合法!";
}
try
{
ITrigger trigger1 = TriggerBuilder.Create()
.WithCronSchedule(cron)
.StartNow()
.Build();
for (int i = 0; i < times; i++)
{
DateTimeOffset? s = trigger1.GetFireTimeAfter(startTime);
DateTime? time = s?.LocalDateTime;
timeSchedule = time?.ToString("F");
}
}
catch (System.Exception e)
{
timeSchedule = "未知时间";
}
return timeSchedule;
}
}
}