forked from anjoy8/Blog.Core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSchedulerCenterServer.cs
More file actions
491 lines (461 loc) · 17.6 KB
/
SchedulerCenterServer.cs
File metadata and controls
491 lines (461 loc) · 17.6 KB
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
using Blog.Core.Model;
using Blog.Core.Model.Models;
using Blog.Core.Model.ViewModels;
using Quartz;
using Quartz.Impl;
using Quartz.Impl.Triggers;
using Quartz.Spi;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Threading.Tasks;
namespace Blog.Core.Tasks
{
/// <summary>
/// 任务调度管理中心
/// </summary>
public class SchedulerCenterServer : ISchedulerCenter
{
private Task<IScheduler> _scheduler;
private readonly IJobFactory _iocjobFactory;
public SchedulerCenterServer(IJobFactory jobFactory)
{
_iocjobFactory = jobFactory;
_scheduler = GetSchedulerAsync();
}
private Task<IScheduler> GetSchedulerAsync()
{
if (_scheduler != null)
return this._scheduler;
else
{
// 从Factory中获取Scheduler实例
NameValueCollection collection = new NameValueCollection
{
{ "quartz.serializer.type", "binary" },
};
StdSchedulerFactory factory = new StdSchedulerFactory(collection);
return _scheduler = factory.GetScheduler();
}
}
/// <summary>
/// 开启任务调度
/// </summary>
/// <returns></returns>
public async Task<MessageModel<string>> StartScheduleAsync()
{
var result = new MessageModel<string>();
try
{
this._scheduler.Result.JobFactory = this._iocjobFactory;
if (!this._scheduler.Result.IsStarted)
{
//等待任务运行完成
await this._scheduler.Result.Start();
await Console.Out.WriteLineAsync("任务调度开启!");
result.success = true;
result.msg = $"任务调度开启成功";
return result;
}
else
{
result.success = false;
result.msg = $"任务调度已经开启";
return result;
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 停止任务调度
/// </summary>
/// <returns></returns>
public async Task<MessageModel<string>> StopScheduleAsync()
{
var result = new MessageModel<string>();
try
{
if (!this._scheduler.Result.IsShutdown)
{
//等待任务运行完成
await this._scheduler.Result.Shutdown();
await Console.Out.WriteLineAsync("任务调度停止!");
result.success = true;
result.msg = $"任务调度停止成功";
return result;
}
else
{
result.success = false;
result.msg = $"任务调度已经停止";
return result;
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 添加一个计划任务(映射程序集指定IJob实现类)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tasksQz"></param>
/// <returns></returns>
public async Task<MessageModel<string>> AddScheduleJobAsync(TasksQz tasksQz)
{
var result = new MessageModel<string>();
if (tasksQz != null)
{
try
{
JobKey jobKey = new JobKey(tasksQz.Id.ToString(), tasksQz.JobGroup);
if (await _scheduler.Result.CheckExists(jobKey))
{
result.success = false;
result.msg = $"该任务计划已经在执行:【{tasksQz.Name}】,请勿重复启动!";
return result;
}
#region 设置开始时间和结束时间
if (tasksQz.BeginTime == null)
{
tasksQz.BeginTime = DateTime.Now;
}
DateTimeOffset starRunTime = DateBuilder.NextGivenSecondDate(tasksQz.BeginTime, 1);//设置开始时间
if (tasksQz.EndTime == null)
{
tasksQz.EndTime = DateTime.MaxValue.AddDays(-1);
}
DateTimeOffset endRunTime = DateBuilder.NextGivenSecondDate(tasksQz.EndTime, 1);//设置暂停时间
#endregion
#region 通过反射获取程序集类型和类
Assembly assembly = Assembly.Load(new AssemblyName(tasksQz.AssemblyName));
Type jobType = assembly.GetType(tasksQz.AssemblyName + "." + tasksQz.ClassName);
#endregion
//判断任务调度是否开启
if (!_scheduler.Result.IsStarted)
{
await StartScheduleAsync();
}
//传入反射出来的执行程序集
IJobDetail job = new JobDetailImpl(tasksQz.Id.ToString(), tasksQz.JobGroup, jobType);
job.JobDataMap.Add("JobParam", tasksQz.JobParams);
ITrigger trigger;
#region 泛型传递
//IJobDetail job = JobBuilder.Create<T>()
// .WithIdentity(sysSchedule.Name, sysSchedule.JobGroup)
// .Build();
#endregion
if (tasksQz.Cron != null && CronExpression.IsValidExpression(tasksQz.Cron) && tasksQz.TriggerType > 0)
{
trigger = CreateCronTrigger(tasksQz);
((CronTriggerImpl)trigger).MisfireInstruction = MisfireInstruction.CronTrigger.DoNothing;
}
else
{
trigger = CreateSimpleTrigger(tasksQz);
}
// 告诉Quartz使用我们的触发器来安排作业
await _scheduler.Result.ScheduleJob(job, trigger);
//await Task.Delay(TimeSpan.FromSeconds(120));
//await Console.Out.WriteLineAsync("关闭了调度器!");
//await _scheduler.Result.Shutdown();
result.success = true;
result.msg = $"【{tasksQz.Name}】成功";
return result;
}
catch (Exception ex)
{
result.success = false;
result.msg = $"任务计划异常:【{ex.Message}】";
return result;
}
}
else
{
result.success = false;
result.msg = $"任务计划不存在:【{tasksQz?.Name}】";
return result;
}
}
/// <summary>
/// 任务是否存在?
/// </summary>
/// <returns></returns>
public async Task<bool> IsExistScheduleJobAsync(TasksQz sysSchedule)
{
JobKey jobKey = new JobKey(sysSchedule.Id.ToString(), sysSchedule.JobGroup);
if (await _scheduler.Result.CheckExists(jobKey))
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 暂停一个指定的计划任务
/// </summary>
/// <returns></returns>
public async Task<MessageModel<string>> StopScheduleJobAsync(TasksQz sysSchedule)
{
var result = new MessageModel<string>();
try
{
JobKey jobKey = new JobKey(sysSchedule.Id.ToString(), sysSchedule.JobGroup);
if (!await _scheduler.Result.CheckExists(jobKey))
{
result.success = false;
result.msg = $"未找到要暂停的任务:【{sysSchedule.Name}】";
return result;
}
else
{
await this._scheduler.Result.DeleteJob(jobKey);
result.success = true;
result.msg = $"【{sysSchedule.Name}】成功";
return result;
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 恢复指定的计划任务
/// </summary>
/// <param name="sysSchedule"></param>
/// <returns></returns>
public async Task<MessageModel<string>> ResumeJob(TasksQz sysSchedule)
{
var result = new MessageModel<string>();
try
{
JobKey jobKey = new JobKey(sysSchedule.Id.ToString(), sysSchedule.JobGroup);
if (!await _scheduler.Result.CheckExists(jobKey))
{
result.success = false;
result.msg = $"未找到要恢复的任务:【{sysSchedule.Name}】";
return result;
}
await this._scheduler.Result.ResumeJob(jobKey);
result.success = true;
result.msg = $"【{sysSchedule.Name}】成功";
return result;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 暂停指定的计划任务
/// </summary>
/// <param name="sysSchedule"></param>
/// <returns></returns>
public async Task<MessageModel<string>> PauseJob(TasksQz sysSchedule)
{
var result = new MessageModel<string>();
try
{
JobKey jobKey = new JobKey(sysSchedule.Id.ToString(), sysSchedule.JobGroup);
if (!await _scheduler.Result.CheckExists(jobKey))
{
result.success = false;
result.msg = $"未找到要暂停的任务:【{sysSchedule.Name}】";
return result;
}
await this._scheduler.Result.PauseJob(jobKey);
result.success = true;
result.msg = $"【{sysSchedule.Name}】成功";
return result;
}
catch (Exception)
{
throw;
}
}
#region 状态状态帮助方法
public async Task<List<TaskInfoDto>> GetTaskStaus(TasksQz sysSchedule)
{
var ls = new List<TaskInfoDto>();
var noTask = new List<TaskInfoDto>{ new TaskInfoDto {
jobId = sysSchedule.Id.ObjToString(),
jobGroup = sysSchedule.JobGroup,
triggerId = "",
triggerGroup = "",
triggerStatus = "不存在"
} };
JobKey jobKey = new JobKey(sysSchedule.Id.ToString(), sysSchedule.JobGroup);
IJobDetail job = await this._scheduler.Result.GetJobDetail(jobKey);
if (job == null)
{
return noTask;
}
//info.Append(string.Format("任务ID:{0}\r\n任务名称:{1}\r\n", job.Key.Name, job.Description));
var triggers = await this._scheduler.Result.GetTriggersOfJob(jobKey);
if (triggers == null || triggers.Count == 0)
{
return noTask;
}
foreach (var trigger in triggers)
{
var triggerStaus = await this._scheduler.Result.GetTriggerState(trigger.Key);
string state = GetTriggerState(triggerStaus.ObjToString());
ls.Add(new TaskInfoDto
{
jobId = job.Key.Name,
jobGroup = job.Key.Group,
triggerId = trigger.Key.Name,
triggerGroup = trigger.Key.Group,
triggerStatus = state
});
//info.Append(string.Format("触发器ID:{0}\r\n触发器名称:{1}\r\n状态:{2}\r\n", item.Key.Name, item.Description, state));
}
return ls;
}
public string GetTriggerState(string key)
{
string state = null;
if (key != null)
key = key.ToUpper();
switch (key)
{
case "1":
state = "暂停";
break;
case "2":
state = "完成";
break;
case "3":
state = "出错";
break;
case "4":
state = "阻塞";
break;
case "0":
state = "正常";
break;
case "-1":
state = "不存在";
break;
case "BLOCKED":
state = "阻塞";
break;
case "COMPLETE":
state = "完成";
break;
case "ERROR":
state = "出错";
break;
case "NONE":
state = "不存在";
break;
case "NORMAL":
state = "正常";
break;
case "PAUSED":
state = "暂停";
break;
}
return state;
}
#endregion
#region 创建触发器帮助方法
/// <summary>
/// 创建SimpleTrigger触发器(简单触发器)
/// </summary>
/// <param name="sysSchedule"></param>
/// <param name="starRunTime"></param>
/// <param name="endRunTime"></param>
/// <returns></returns>
private ITrigger CreateSimpleTrigger(TasksQz sysSchedule)
{
if (sysSchedule.CycleRunTimes > 0)
{
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity(sysSchedule.Id.ToString(), sysSchedule.JobGroup)
.StartAt(sysSchedule.BeginTime.Value)
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(sysSchedule.IntervalSecond)
.WithRepeatCount(sysSchedule.CycleRunTimes - 1))
.EndAt(sysSchedule.EndTime.Value)
.Build();
return trigger;
}
else
{
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity(sysSchedule.Id.ToString(), sysSchedule.JobGroup)
.StartAt(sysSchedule.BeginTime.Value)
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(sysSchedule.IntervalSecond)
.RepeatForever()
)
.EndAt(sysSchedule.EndTime.Value)
.Build();
return trigger;
}
// 触发作业立即运行,然后每10秒重复一次,无限循环
}
/// <summary>
/// 创建类型Cron的触发器
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
private ITrigger CreateCronTrigger(TasksQz sysSchedule)
{
// 作业触发器
return TriggerBuilder.Create()
.WithIdentity(sysSchedule.Id.ToString(), sysSchedule.JobGroup)
.StartAt(sysSchedule.BeginTime.Value)//开始时间
.EndAt(sysSchedule.EndTime.Value)//结束数据
.WithCronSchedule(sysSchedule.Cron)//指定cron表达式
.ForJob(sysSchedule.Id.ToString(), sysSchedule.JobGroup)//作业名称
.Build();
}
#endregion
/// <summary>
/// 立即执行 一个任务
/// </summary>
/// <param name="tasksQz"></param>
/// <returns></returns>
public async Task<MessageModel<string>> ExecuteJobAsync(TasksQz tasksQz)
{
var result = new MessageModel<string>();
try
{
JobKey jobKey = new JobKey(tasksQz.Id.ToString(), tasksQz.JobGroup);
//判断任务是否存在,存在则 触发一次,不存在则先添加一个任务,触发以后再 停止任务
if (!await _scheduler.Result.CheckExists(jobKey))
{
//不存在 则 添加一个计划任务
await AddScheduleJobAsync(tasksQz);
//触发执行一次
await _scheduler.Result.TriggerJob(jobKey);
//停止任务
await StopScheduleJobAsync(tasksQz);
result.success = true;
result.msg = $"立即执行计划任务:【{tasksQz.Name}】成功";
}
else
{
await _scheduler.Result.TriggerJob(jobKey);
result.success = true;
result.msg = $"立即执行计划任务:【{tasksQz.Name}】成功";
}
}
catch (Exception ex)
{
result.msg = $"立即执行计划任务失败:【{ex.Message}】";
}
return result;
}
}
}