using Microsoft.Extensions.DependencyInjection; using Quartz; using Quartz.Impl; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace wispro.sp.api.Job { public class QuartzUtil { private static ISchedulerFactory _schedulerFactory; private static IScheduler _scheduler; /// /// 添加任务 /// /// 类 /// 键 /// 触发器 public static async Task Add(Type type, JobKey jobKey, ITrigger trigger = null) { await Init(); if (trigger == null) { trigger = TriggerBuilder.Create() .WithDescription("default") .WithSimpleSchedule(x => x.WithMisfireHandlingInstructionFireNow().WithRepeatCount(-1)) .Build(); } var job = JobBuilder.Create(type) .WithIdentity(jobKey) .Build(); await _scheduler.ScheduleJob(job, trigger); } public static async Task Add(IJobDetail job, ITrigger trigger = null) { await Init(); if (trigger == null) { trigger = TriggerBuilder.Create() .WithDescription("default") .WithSimpleSchedule(x => x.WithMisfireHandlingInstructionFireNow().WithRepeatCount(-1)) .Build(); } await _scheduler.ScheduleJob(job, trigger); } public static async Task AddMailJob(string Subject,string Body,string toName,string To,string AttachFiles=null) { await Init(); var trigger = TriggerBuilder.Create() .WithDescription("发送邮件通知") .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).WithRepeatCount(0)) .Build(); var job = JobBuilder.Create(typeof(MailJob)) .Build(); job.JobDataMap.Put("Subject",Subject); job.JobDataMap.Put("Body", Body); job.JobDataMap.Put("To", To); job.JobDataMap.Put("Reciever", toName); job.JobDataMap.Put("AttachFiles", AttachFiles); await _scheduler.ScheduleJob(job, trigger); } /// /// 恢复任务 /// /// 键 public static async Task Resume(JobKey jobKey) { Init(); _scheduler = await _schedulerFactory.GetScheduler(); //LogUtil.Debug($"恢复任务{jobKey.Group},{jobKey.Name}"); await _scheduler.ResumeJob(jobKey); } /// /// 停止任务 /// /// 键 public static async Task Stop(JobKey jobKey) { Init(); _scheduler = await _schedulerFactory.GetScheduler(); //LogUtil.Debug($"暂停任务{jobKey.Group},{jobKey.Name}"); await _scheduler.PauseJob(jobKey); } /// /// 初始化 /// private static async Task Init() { if (_scheduler == null) { _schedulerFactory = new StdSchedulerFactory();// ServiceLocator.Services.GetService(); _scheduler = await _schedulerFactory.GetScheduler(); await _scheduler.Start(); } } } }