Quartz定时任务帮助类

  1 using Quartz;
  2 using Quartz.Impl;
  3 using System;
  4 using System.Collections.Generic;
  5 using System.Collections.Specialized;
  6 using System.Linq;
  7 using System.Text;
  8 using System.Threading.Tasks;
  9 
 10 namespace CRM.ThirdAPITools.QuartzHelper
 11 {
 12     /// <summary>
 13     /// Quartz定时任务帮助类: Quartz表达式设计器:http://cron.qqe2.com/
 14     /// </summary>
 15     public class QuartzHelper
 16     {
 17         // Fields
 18         private static object oLock = new object();
 19         private static Dictionary<string, QuartzKey> quartzCache = new Dictionary<string, QuartzKey>();
 20         private const string QuartzHelperScheulerName = "QuartzHelperScheulerName";
 21         private static IScheduler sched = null;
 22         private static ISchedulerFactory sf = null;
 23         // Methods
 24         static QuartzHelper()
 25         {
 26             NameValueCollection props = new NameValueCollection();
 27             props.Add("quartz.scheduler.instanceName", "QuartzHelperScheulerName");
 28             sf = new StdSchedulerFactory(props);
 29             sched = sf.GetScheduler();
 30         }
 31         /// <summary>
 32         /// 关闭
 33         /// </summary>
 34         public static void Close()
 35         {
 36             GetScheduler().Shutdown(true);
 37         }
 38         /// <summary>
 39         /// 删除
 40         /// </summary>
 41         /// <param name="jobKey"></param>
 42         public static void Close(object jobKey)
 43         {
 44             if (jobKey is JobKey)
 45             {
 46                 GetScheduler().DeleteJob(jobKey as JobKey);
 47             }
 48         }
 49         /// <summary>
 50         /// 指定日期执行
 51         /// </summary>
 52         /// <param name="action">调用的方法</param>
 53         /// <param name="date">指定日期</param>
 54         /// <param name="dataMap">传输数据映射</param>
 55         /// <param name="jobName">任务名称</param>
 56         /// <returns></returns>
 57         public static QuartzKey ExecuteAtDate(Action<Dictionary<string, object>> action, DateTime date, Dictionary<string, object> dataMap = null, string jobName = null)
 58         {
 59             return Start(action, delegate (TriggerBuilder p)
 60             {
 61                 p.WithCronSchedule(BuilderCronExpression(date));
 62             }, dataMap, jobName);
 63         }
 64         /// <summary>
 65         /// 按表达式执行:
 66         /// Quartz表达式设计器:http://cron.qqe2.com/
 67         /// </summary>
 68         /// <param name="action">调用的方法</param>
 69         /// <param name="cronExpression">表达式</param>
 70         /// <param name="dataMap">传输数据映射</param>
 71         /// <param name="jobName">任务名称</param>
 72         /// <returns></returns>
 73         public static QuartzKey ExecuteAtTime(Action<Dictionary<string, object>> action, string cronExpression, Dictionary<string, object> dataMap = null, string jobName = null)
 74         {
 75             return Start(action, delegate (TriggerBuilder p)
 76             {
 77                 p.WithCronSchedule(cronExpression);
 78             }, dataMap, jobName);
 79         }
 80         /// <summary>
 81         /// 间隔执行
 82         /// </summary>
 83         /// <param name="action">调用的方法</param>
 84         /// <param name="interval">时间间隔</param>
 85         /// <param name="dataMap">传输数据映射</param>
 86         public static void ExecuteInterval(Action<Dictionary<string, object>> action, TimeSpan interval, Dictionary<string, object> dataMap = null)
 87         {
 88             Action<TriggerBuilder> action2 = null;
 89             lock (oLock)
 90             {
 91                 if (action2 == null)
 92                 {
 93                     action2 = p => p.WithSimpleSchedule(p1 => p1.WithInterval(interval));
 94                 }
 95                 Start(action, action2, dataMap, null);
 96             }
 97         }
 98         /// <summary>
 99         /// 获取调度名称
100         /// </summary>
101         /// <returns></returns>
102         public static IScheduler GetScheduler()
103         {
104             ISchedulerFactory factory = new StdSchedulerFactory();
105             return factory.GetScheduler("QuartzHelperScheulerName");
106         }
107         /// <summary>
108         /// 任务调度是否开始
109         /// </summary>
110         /// <returns></returns>
111         public static bool IsStart()
112         {
113             return ((GetScheduler() != null) && GetScheduler().IsStarted);
114         }
115         /// <summary>
116         /// DateTime转为Quartz表达式
117         /// </summary>
118         /// <param name="date"></param>
119         /// <returns></returns>
120         public static string BuilderCronExpression(DateTime date)
121         {
122             string cron = string.Empty;
123             cron = string.Format("{0} {1} {2} {3} {4} ?", date.Second, date.Minute, date.Hour, date.Day, date.Month);
124             return cron;
125         }
126         /// <summary>
127         /// 启用调度任务
128         /// </summary>
129         /// <param name="action">方法</param>
130         /// <param name="action2">构建的出发实例</param>
131         /// <param name="dataMap">传输数据映射</param>
132         /// <param name="jobName">任务名称</param>
133         /// <returns></returns>
134         private static QuartzKey Start(Action<Dictionary<string, object>> action, Action<TriggerBuilder> action2, Dictionary<string, object> dataMap, string jobName)
135         {
136             QuartzKey key = new QuartzKey();
137             if (jobName != null)
138             {
139                 if (quartzCache.ContainsKey(jobName))
140                 {
141                     key = quartzCache[jobName];
142                 }
143                 else
144                 {
145                     quartzCache.Add(jobName, key);
146                 }
147             }
148             jobName = jobName ?? Guid.NewGuid().ToString("D");
149             string group = "group_" + jobName;
150             string name = "trigger_" + jobName;
151             IJobDetail jobDetail = JobBuilder.Create(typeof(QuartzJob)).WithIdentity(jobName, group).Build();
152             TriggerBuilder builder = TriggerBuilder.Create().WithIdentity(name, group);
153             action2(builder);
154             ITrigger trigger = builder.Build();
155             if (quartzCache.ContainsKey(jobName))
156             {
157                 quartzCache[jobName].JobKey = jobDetail.Key;
158                 quartzCache[jobName].TriggerKey = trigger.Key;
159                 quartzCache[jobName].Logs.Add(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " 调度任务已经启动。");
160             }
161             jobDetail.JobDataMap.Add("dataMap", dataMap);
162             jobDetail.JobDataMap.Add("action", action);
163             jobDetail.JobDataMap.Add("jobName", jobName);
164             jobDetail.JobDataMap.Add("quartzCache", quartzCache);
165             sched.ScheduleJob(jobDetail, new Quartz.Collection.HashSet<ITrigger> { trigger }, true);
166             sched.Start();
167             return key;
168         }
169     }
170     public class QuartzJob : IJob
171     {
172         // Methods
173         public void Execute(IJobExecutionContext context)
174         {
175             Dictionary<string, object> dictionary = context.JobDetail.JobDataMap["dataMap"] as Dictionary<string, object>;
176             string key = context.JobDetail.JobDataMap["jobName"] as string;
177             Dictionary<string, QuartzKey> dictionary2 = context.JobDetail.JobDataMap["quartzCache"] as Dictionary<string, QuartzKey>;
178             try
179             {
180                 (context.JobDetail.JobDataMap["action"] as Action<Dictionary<string, object>>)(dictionary);
181                 if (dictionary2.ContainsKey(key))
182                 {
183                     dictionary2[key].Logs.Add(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " 任务执行成功。");
184                 }
185             }
186             catch (Exception exception)
187             {
188                 if (dictionary2.ContainsKey(key))
189                 {
190                     dictionary2[key].Logs.Add(exception.Message);
191                 }
192             }
193         }
194     }
195     public class QuartzKey
196     {
197         // Methods
198         public QuartzKey()
199         {
200             this.Logs = new List<string>();
201         }
202 
203         // Properties
204         public JobKey JobKey { get; set; }
205 
206         public List<string> Logs { get; set; }
207 
208         public TriggerKey TriggerKey { get; set; }
209     }
210 }
原文地址:https://www.cnblogs.com/Andy-Blog/p/10114942.html