VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > 简明python教程 >
  • Quartz3.0定时任务学习之异步调度器

前言

Quartz3与Quartz2的主要区别有两点:

1,Quartz3将它的资源类库拆的更细了,比如,想使用Quartz3开发,最少要引用Quartz,Quartz.Jobs,Quartz.Plugins这三个类库。

2,Quartz3整体上使用的是异步创建实例,所以我们使用时就必须要async,await的语法。

下面我们用Quartz3来做一个任务调度。

创建调度器管理类

首先创建Jops类库,然后在Nuget中搜索Quartz.Plugins;如下图:

因为Quartz.Plugins依赖于Quartz,所以引入Quartz.Plugins就会自动引入Quartz。

然后我们创建任务调度管理类—ScheduleControler。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
public class ScheduleControler
{
    private static IScheduler scheduler;
    private static Dictionary<IJobDetail, IReadOnlyCollection<ITrigger>> dicJop = new Dictionary<IJobDetail, IReadOnlyCollection<ITrigger>>();
    
    private static int triggerId = 0;
    private static string defaultGroupName = "默认组";
    /// <summary>
    /// 初始化调度器
    /// </summary>
    /// <returns></returns>
    public static async Task Init()
    {
        try
        {
            //quartz.config配置文件里的键值对
            //NameValueCollection props = new NameValueCollection
            //{
            //   { "quartz.serializer.type", "binary" }
            //};
            StdSchedulerFactory factory = new StdSchedulerFactory();
            scheduler = await factory.GetScheduler();
            await scheduler.Start();
        }
        catch (SchedulerException se)
        {
            System.Console.WriteLine(se);
        }
    }
    /// <summary>
    /// 运行调度器任务
    /// </summary>
    /// <returns></returns>
    public static async Task Run()
    {
        try
        {
            await scheduler.ScheduleJobs(dicJop, true);
        }
        catch (SchedulerException se)
        {
            System.Console.WriteLine(se);
        }
    }
    /// <summary>
    /// 关闭调度器
    /// </summary>
    /// <returns></returns>
    public static async Task Shutdown()
    {
        try
        {
            await scheduler.Shutdown();
        }
        catch (SchedulerException se)
        {
            System.Console.WriteLine(se);
        }
    }
    /// <summary>
    /// 添加任务
    /// </summary>
    /// <typeparam name="T">任务类型,继承Ijop</typeparam>
    /// <param name="jopName">任务名</param>
    /// <param name="Interval">运行间隔时间/秒**最小为1秒</param>
    /// <param name="period">等待启动时间/秒**-1为马上启动</param>
    /// <param name="repeatTime">重复次数**-1为永远运行</param>
    /// <param name="endAt">在指定时间后结束/秒**0为不指定结束时间,默认值0</param>
    public static void PushJop<T>(string jopName, int Interval, int period=-1,int repeatTime=-1,int endAt=0)  where T:IJob
        {
            try
            {
                if (Interval <= 0)
                {
                    Interval = 1;
                }
                if (period < -1)
                {
                    period = -1;
                }
                if (repeatTime < -1)
                {
                    repeatTime = -1;
                }
                if (endAt < 0)
                {
                    endAt = -1;
                }
                IJobDetail job = JobBuilder.Create<T>().WithIdentity(jopName, defaultGroupName).UsingJobData("Name""IJobDetail").Build();
            
                var triggerBuilder  = TriggerBuilder.Create().WithIdentity($"{jopName}.trigger{triggerId}", defaultGroupName);
                if (period == -1)
                {
                    triggerBuilder = triggerBuilder.StartNow();
                }
                else
                {
                    DateTimeOffset dateTimeOffset = DateTimeOffset.Now.AddSeconds(period);
                    triggerBuilder = triggerBuilder.StartAt(dateTimeOffset);
                }
                if (endAt > 0)
                {
                    triggerBuilder = triggerBuilder.EndAt(new DateTimeOffset(DateTime.Now.AddSeconds(endAt)));
                
                if (repeatTime == -1)
                {
                    triggerBuilder = triggerBuilder.WithSimpleSchedule(x => x.WithIntervalInSeconds(Interval).RepeatForever()); 
                }
                else
                {
                    triggerBuilder = triggerBuilder.WithSimpleSchedule(x => x.WithRepeatCount(Interval).WithRepeatCount(repeatTime));
                }
                ITrigger trigger = triggerBuilder.UsingJobData("Name""ITrigger")
                     .WithPriority(triggerId)//设置触发器优先级,当有多个触发器在相同时间出发时,优先级最高[数字最大]的优先
                     .Build();
                dicJop.Add(job, new HashSet<ITrigger>() { trigger });
                triggerId++;
            }
            catch (SchedulerException se)
            {
                System.Console.WriteLine(se);
            }
        }
    public static void PushJop<T>(string jopName, string cronExpress) where T : IJob
    {
        try
        {
            IJobDetail job = JobBuilder.Create<T>().WithIdentity(jopName, defaultGroupName).UsingJobData("Name""IJobDetail").Build();
            ITrigger trigger = TriggerBuilder.Create()
               .WithIdentity($"{jopName}.trigger{triggerId}", defaultGroupName)
               .WithCronSchedule(cronExpress)
               .ForJob(job)
               .Build();
            dicJop.Add(job, new HashSet<ITrigger>() { trigger });
            triggerId++;
        }
        catch (SchedulerException se)
        {
            System.Console.WriteLine(se);
        }
    }
}

相关教程