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 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 DeleteTask(string jobName, string jobGroup = "default") { return await _scheduler.DeleteJob(new JobKey(jobName, jobGroup)); } public async Task DeleteTasks(ReadOnlyCollection jobKeys) { return await _scheduler.DeleteJobs(jobKeys); } /// /// Corn表达式的运行时间 /// /// 表达式 /// 计算次数 /// 开始时间 /// 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; } } }