c# Quartz.net的简单封装
分享一个以前封装的Quartz.net类。
新建一个QuartzClass类库项目。nuget控制台输入
添加Quartz.net的引用。
我们新建一个JobBase.cs文件,里面有一个Run方法。之后所有的Job都需继承这个基类,并实现Run方法。
namespace LY.QuartzClass { public abstract class JobBase { public abstract void Run(); } }
之后新增一个JobInstance.cs类。这个类主要实现IJob接口。
using Quartz; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LY.QuartzClass { public class JobInstance : IJob { public void Execute(IJobExecutionContext context) { IDictionary<string, object> jobs = context.JobDetail.JobDataMap; if (jobs != null) { foreach (var item in jobs.Values) { try { JobBase jobObj = item as JobBase; jobObj.Run(); } catch { } } } } } }
在JobInstance类的Execute方法中,我们从JobDataMap中取出JobBase实体,并执行Run方法。
下面我们新增一个JobManager.cs类,类内只有一个简单的AddJob方法
using Quartz; using Quartz.Impl; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LY.QuartzClass { public class JobManage { IScheduler schedudler; public JobManage() { schedudler = StdSchedulerFactory.GetDefaultScheduler(); schedudler.Start(); } public void AddJob<T>(int Second) where T : JobBase { JobBase jbobj = Activator.CreateInstance<T>(); IDictionary<string, object> jbData = new Dictionary<string, object>(); jbData.Add("name", jbobj); IJobDetail job1 = JobBuilder.Create<JobInstance>() .SetJobData(new JobDataMap(jbData)).Build(); ITrigger trigger1 = TriggerBuilder.Create() .StartNow() .WithSimpleSchedule(x => x.WithIntervalInSeconds(Second) .RepeatForever()).Build(); schedudler.ScheduleJob(job1, trigger1); } public void AddJob<T>(string rule) where T : JobBase { JobBase jbInstance = Activator.CreateInstance<T>(); IDictionary<string, object> jbData = new Dictionary<string, object>(); jbData.Add("name", jbInstance); IJobDetail job1 = JobBuilder.Create<JobInstance>() .SetJobData(new JobDataMap(jbData)).Build(); ITrigger trigger1 = TriggerBuilder.Create() .StartNow() .WithCronSchedule(rule).Build(); schedudler.ScheduleJob(job1, trigger1); } } }
在AddJob时,将Job传入JobData中。
下面我们进行调用Test。
新建一个窗体项目,并添加对LY.QuartzClass项目的引用。
新增三个Job类,继承自JobBase
public class FirstJob : JobBase { public override void Run() { Console.WriteLine(DateTime.Now.ToString()); } }
public class SecondJob : JobBase { public override void Run() { Console.WriteLine(DateTime.Now.ToString() + ":Hello"); } }
public class ThirdJob : JobBase { public override void Run() { Console.WriteLine(DateTime.Now.ToString() + ":CronTest"); } }
在窗体中进行调用
private void button1_Click(object sender, EventArgs e) { JobManage job = new JobManage(); job.AddJob<FirstJob>(3); job.AddJob<SecondJob>(6); job.AddJob<ThirdJob>("0/5 0-58 9 * * ?"); }
结果如下: