Quartz.Net使用

Quartz.Net使用

标签:Quartz.Net


在最近工作中,需要在不同时间及不同条件下定时发送通知及消息,最初使用System.Timers.Timer实现。虽然使用简单,随着需要定时处理的任务增多,考虑到System.Timers.Timer如下缺点:

  • Timer没有持久化机制;
  • Timer的调度没有弹性,仅能定时触发,不可自由配置触发时间点;
  • Timer不能利用线程池,每一个Timer需要开启一个线程;
  • 每个Timer中的任务为串行执行,同一时间只能有一个任务在执行。前一个任务执行失败影响后面任务的执行;

Quartz.Net的以下优点可解决以上问题

  • 使用灵活,有多种使用方式(eg XML配置任务,),且可以混合使用;
  • 支持集群,作业分组,及作业远程管理;
  • 可自定义精细的时间管理;
  • 支持数据库,可持久化。

安装

  • 通过NuGet安装Quartz.Net

说明

  • 每一个任务需要继承接口IJob,并实现Execute(IJobExecutionContext context),该方法为每个Job需要做的具体处理;

代码示例

  • 代码创建job示例
  private static void Main(string[] args)
        {
            try
            {
                WatchFile();
                var fileName = Path.Combine(Environment.CurrentDirectory, "log4config.config");
                XmlConfigurator.ConfigureAndWatch(new FileInfo(fileName));
                StdSchedulerFactory factory = new StdSchedulerFactory();
                IScheduler scheduler = factory.GetScheduler();
                // 启动任务
                scheduler.Start();
                // 创建Job,可通过JobDataMap传递数据
                IJobDetail job = JobBuilder.Create<HelloJob>()
                    .WithIdentity("job1", "group1")
                    .UsingJobData("jobSays", "Hello World!")
                    .UsingJobData("myFloatValue", 3.141f)
                    .Build();
                //创建trigger
                ITrigger trigger = TriggerBuilder.Create()
                    .WithIdentity("trigger1", "group1")
                    .StartNow()
                    .WithSimpleSchedule(x => x.WithIntervalInSeconds(10).RepeatForever())
                    .Build();
                //把job,trigger加入调度器
                scheduler.ScheduleJob(job, trigger);
                //关闭调度器
                scheduler.Shutdown();
            }
            catch (Exception ex)
            {
                LogHelper.Error("Main" + ex);
            }
            Console.WriteLine("Press any key to close the application");
            Console.ReadKey();
        }
    public class HelloJob : IJob
    {
        public void  Execute(IJobExecutionContext context)
        {
            JobKey key = context.JobDetail.Key;
            //获取执行的数据
            JobDataMap dataMap = context.JobDetail.JobDataMap;
            string jobSays = dataMap.GetString("jobSays");
            float myFloatValue = dataMap.GetFloat("myFloatValue");
             Console.Error.WriteLineAsync("Instance " + key + " of DumbJob says: " + jobSays + ", and val is: " + myFloatValue);

        }
    }
    pub    
  • XML方式配置Job、Trigger代码示例
    1) 在quartz_jobs.xml为配置JobTrigger的文件
    配置文件示例:
<?xml version="1.0" encoding="utf-8" ?>
<job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0">
  <processing-directives>
    <overwrite-existing-data>true</overwrite-existing-data>
  </processing-directives>
  <schedule>
    <job>
      <name>CommonIMRemindJob</name>
      <group>IMRemindJob</group>
      <description>IMRemindJob</description>
      <job-type>NXIN.Qlw.JobServices.CommonIMRemindJobService,NXIN.Qlw.JobServices</job-type>
      <durable>true</durable>
      <recover>true</recover>
    </job>
    <trigger>
      <simple>
        <name>CommonIMRemindTrigger</name>
        <group>IMRemindJob</group>
        <description>CommonIMRemindTrigger</description>
        <job-name>CommonIMRemindJob</job-name>
        <job-group>IMRemindJob</job-group>
        <misfire-instruction>SmartPolicy</misfire-instruction>
        <repeat-count>-1</repeat-count>
        <repeat-interval>300000</repeat-interval>
      </simple>
    </trigger>
  </schedule>
</job-scheduling-data>
2)实现示例
  private static void InitScheduler()
        {
            try
            {
                NameValueCollection props = new NameValueCollection
                {
                    { "quartz.serializer", "binary" }
                };

                XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper());

                StdSchedulerFactory factory = new StdSchedulerFactory(props);
                IScheduler scheduler = factory.GetScheduler();
                processor.ProcessFileAndScheduleJobs("~/quartz_jobs.xml", scheduler);
                scheduler.Start();
            }
            catch (SchedulerException se)
            {
                LogHelper.Error("/Main/RunProgramRunExample" + se);
            }
        }

猜你喜欢

转载自www.cnblogs.com/echogreat/p/8920922.html