c# Quartz.net的簡單封裝

liuyong111發表於2018-07-03

分享一個以前封裝的Quartz.net類。

新建一個QuartzClass類庫專案。nuget控制檯輸入

image.png

 

新增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 * * ?");
}

 

結果如下:

 

 
image.png

相關文章