Quartz C # in easy to understand the timing of realization of tasks

Address reprint: https://www.cnblogs.com/wendj/archive/2018/09/18/9670412.html 

As an excellent open source framework for scheduling, Quartz has the following characteristics:

  1. Powerful scheduling features, such as support for a variety of scheduling methods, to meet a variety of conventional and special needs;
  2. Flexible application methods, such as support for a variety of combinations and scheduling tasks, supports a variety of scheduling data storage;
  3. Distributed and clustering capabilities, after the acquisition of Terracotta made to further enhance the functionality of the original basis.

      Further, as a default scheduling framework Spring, Quartz is easily integrated flexible scheduling function implemented Spring configurable.

    Scheduling quartz core elements:

  1. Scheduler: Task scheduler, task scheduling is the actual implementation of the controller. In the spring encapsulated by SchedulerFactoryBean.
  2. Trigger: trigger time for task scheduling rule definition, there SimpleTrigger, CronTrigger, DateIntervalTrigger and NthIncludedDayTrigger, wherein CronTrigger more used, this paper describes manner. CronTrigger CronTriggerFactoryBean in the spring in the package.
  3. Calendar: It is a collection of calendar specific point in time. A trigger may comprise a plurality of Calendar, so as to exclude or include certain point of time.
  4. JobDetail: Job implementation class used to describe the static and other related information, such as Job name, and other information associated with the listener. There are two implementations JobDetailFactoryBean and MethodInvokingJobDetailFactoryBean in the spring, if only need to perform a task scheduling method of a class, you can call by MethodInvokingJobDetailFactoryBean.
  5. Job: an interface is only one way void execute (JobExecutionContext context), defined by the interface developers to implement the task runs, the JobExecutionContext class provides information about the scheduling context. Information stored in JobDataMap instance Job runtime. Job interface to achieve the task, the default is stateless, To Job is set to have a state, is to achieve the Job @DisallowConcurrentExecution add annotations in quartz (formerly realize StatefulJob interface has now been Deprecated), in the spring Combination of parameters can be configured concurrent job detail spring configuration file.

I am here simply recording process and use the code:

1: First of all references to Quartz components

2:using Quartz;using Quartz.Impl;

Note: Create a console project locally, copy the following code in the past to use, you only need to override the Execute method. Quartz3.0 and above versions are asynchronous used, the following version 3.0 does not use asynchronous, using the same method

The main function entry file:

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
using  BackgroundTask.job;
using  log4net;
using  Quartz;
using  Quartz.Impl;
using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Text;
using  System.Threading.Tasks;
 
namespace  BackgroundTask
{
     class  Program
     {
         private  static  readonly  ILog _log = LogManager.GetLogger( typeof (Program));
 
         private  static  readonly  string  tiggerName =  "TestJobTrigger" ;
         private  static  readonly  string  gropName =  "TestJobTriggerGrop" ;
         private  static  readonly  string  jobName =  "TestJob" ;
         //从工厂中获取一个调度器实例化
         private  static  IScheduler scheduler =  null ;
 
 
         static  void  Main( string [] args)
         {
             Console.WriteLine( "开始任务...." );
             _log.Debug( "开始任务...." );
             Start();
 
         }
 
         private  static  async  void  Start()
         {
             //从工厂中获取一个调度器实例化
             scheduler = await StdSchedulerFactory.GetDefaultScheduler();
             await scheduler.Start();
 
 
             //创建一个作业
             IJobDetail job1 = JobBuilder.Create<TestJob>()
              .WithIdentity(jobName, gropName)
              .UsingJobData( "key" , "value" ) // 传递参数 在Execute方法中获取(以什么类型值传入,取值就用相应的类型方法取值)
              .Build();
 
             // 创建触发器
             ITrigger trigger1 = TriggerBuilder.Create()
                                         .WithIdentity(tiggerName, gropName)
                                         .StartNow()                         //现在开始
                                         .WithSimpleSchedule(x => x          //触发时间,10秒一次。
                                             .WithIntervalInSeconds(10)
                                             .RepeatForever())               //不间断重复执行
                                         .Build();
 
 
             await scheduler.ScheduleJob(job1, trigger1);       //把作业,触发器加入调度器。
 
             Console.ReadKey();
 
             // 清除任务和触发器
             ClearJobTrigger();
         }
 
         /// <summary>
         /// 清除任务和触发器
         /// </summary>
         private  static  void  ClearJobTrigger()
         {
             TriggerKey triggerKey =  new  TriggerKey(tiggerName, gropName);
             JobKey jobKey =  new  JobKey(jobName, gropName);
             if  (scheduler !=  null )
             {
                 scheduler.PauseTrigger(triggerKey);
                 scheduler.UnscheduleJob(triggerKey);
                 scheduler.DeleteJob(jobKey);
                 scheduler.Shutdown(); // 关闭
             }
 
         }
 
     }
 
}

  

实现IJob 接口的任务文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using  log4net;
using  Quartz;
using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Text;
using  System.Threading.Tasks;
 
namespace  BackgroundTask.job
{
     public  class  TestJob : IJob
     {
         private  readonly  ILog _log = LogManager.GetLogger( typeof (TestJob));
         /// <summary>
         /// 测试作业
         /// </summary>
         /// <param name="context"></param>
         /// <returns></returns>
         public  async Task Execute(IJobExecutionContext context)
         {

        JobDataMap dataMap = context.JobDetail.JobDataMap;
        string k = dataMap.GetString("key");//获取参数(可根据传递的类型使用GetInt、GetFloat、GetString.....)

1
2
3
4
5
6
7
8
             _log.Debug( "run TestJob debug" );
             _log.Error( "run TestJob error" );
             _log.Info( "run TestJob info" );
             // 在这里处理你的任务
             
         }
     }
}<br><br>

Guess you like

Origin www.cnblogs.com/blogsaspx/p/10995947.html