zoukankan      html  css  js  c++  java
  • Quartz.net 2.x 学习笔记01

    Quartz.net 2.0 201249日发布了Released版本,到目前(2014-12-08)为止是2.3

    Quartz.net 项目地址:http://www.quartz-scheduler.net/

    官方2.x 教程:http://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/index.html

     

    Quartz.net 2.x.net中的使用

    Quartz.net 的介绍和下载网上很多。Quartz.net是一个开源的专门用来处理我们日常所说的定时任务,就像你想让程序某些时间去做一些事情(例如:每天晚上0点的时候定时给领导发数据邮件)。

     

    首先新建一个控制台应用程序:

     

    第二步,添加Quartz.net的引用(有以下2种方式)

    一、Quartz.net的引用可以自己下载dll自行引用(这里要提醒一下,quartz.net还依赖于Common.Logging.dll,同时版本要一致,下载可以去官方下载:http://www.quartz-scheduler.net/ 和Common.Logging连同一起)

    二、直接使用NuGet添加引用

     

    在搜索处输入quartz.net搜索安装即可(目前是2.3)

     

     

    同上图可以看到它有个依赖项Common.Logging,安装时会自动将Common.Logging也安装上,所以推荐使用NuGet的引用方式。

    当然NuGet你也可以通过命令的方式安装:Install-Package Quartz

     

    开始之前先来说一下Quartz.net的配置(Configuration)

    也有几种方式 (以下是自己的理解+翻译:http://www.quartz-scheduler.net/documentation/quartz-2.x/quick-start.html

    1、在你的程序中使用NameValueCollection的方式给定时器工厂(scheduler factory)提供参数

    2、在程序的config文件中使用quartz配置节

    3、在程序的根目录上使用一个命名为quartz.config的文件

    三种方式其实是一样的,都是提供键值对的参数值 (方便以后修改的话,建议使用2或者3

     

    例如使用quartz.config 会看到是如下大概的形式:

    quartz.scheduler.instanceName = MyScheduler

    quartz.threadPool.threadCount = 3

    quartz.jobStore.type = Quartz.Simpl.RAMJobStore, Quartz

     

    上面简单的意思就是

    定时器的名字是MyScheduler,线程池中分配3个线程,也就是说同时最多只能有3个任务在执行,第3个配置是任务的存储类型,因为默认Quartz的所有数据(JobDetailtriggers)是保存在内存中的,上面是配置存入数据库(可以去下载quartz.net的源码,你会看到它提供了相关的建表的语句,可以直接使用它的表,当然是靠配置去使用-------表有点多,并且我目前的业务没有那么复杂,如果使用,我会选择自己建表存储)。

     

    第三步、下面开始一个简单的任务

    我还是按照官方的教程一步一步来,将控制台的Program.cs修改成如下代码:

     

    using System.Threading.Tasks;
    using Quartz;
    using Quartz.Impl;
    
    namespace Quartz001
    {
        class Program
        {
            
            static void Main(string[] args)
            {
                //配置Common.Logging的日志输出为控制台的方式
                Common.Logging.LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter { Level = Common.Logging.LogLevel.Info };
    
                try
                {
                    //通过工厂得到Scheduler的一个实例
                    IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
    
                    //开启
                    scheduler.Start();
    
                    Thread.Sleep(TimeSpan.FromSeconds(10));   
    
                    //关闭定时器
                    scheduler.Shutdown();
    
                    Console.ReadKey();
                }
                catch (SchedulerException ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }
    }

     

     

    F5运行,输出

     

     

    上面只是Quartz.net的最简单的开启和关闭

    下面添加一个执行任务,Quartz的任务也很简单,只需要让任务类继承并实现IJob接口

    右击控制台应用程序添加一个类HelloJob.cs

    using Quartz;
    
    namespace Quartz001
    {
        public class HelloJob:IJob
        {
            public void Execute(IJobExecutionContext context)
            {
                Console.WriteLine("我来自HelloJob任务");
            }
        }
    }

     

    然后对Program.cs代码做一些修改:

    using System.Threading.Tasks;
    using Quartz;
    using Quartz.Impl;
    
    namespace Quartz001
    {
        class Program
        {
            
            static void Main(string[] args)
            {
                //配置Common.Logging的日志输出为控制台的方式
                Common.Logging.LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter { Level = Common.Logging.LogLevel.Info };
    
                try
                {
                    //通过工厂得到Scheduler的一个实例
                    IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
    
                    //开启
                    scheduler.Start();
    
                    //使用JobBuilder合建一个任务并和我们的HelloJob绑定在一起(注意Job的Key-相当于唯一标识)
                    IJobDetail job = JobBuilder.Create<HelloJob>()
                        .WithIdentity("job1", "group1")
                        .Build(); 
    
                    //任务触发器--StartNow()立即执行,执行间隔10s,一直执行
                    ITrigger trigger = TriggerBuilder.Create()
                        .WithIdentity("trigger1", "group1")
                        .StartNow()
                        .WithSimpleSchedule(x => x.WithIntervalInSeconds(10)
                            .RepeatForever())
                        .Build();
    
                    //告诉Quartz用上面的触发器去定时执行job
                    scheduler.ScheduleJob(job, trigger);
    
                    Thread.Sleep(TimeSpan.FromSeconds(60));
    
                    //关闭定时器
                    scheduler.Shutdown();                
                }
                catch (SchedulerException ex)
                {
                    Console.WriteLine(ex);
                }
    
                Console.WriteLine("按任意键退出!");
                Console.ReadKey();
            }
        }
    }

     

    执行结果:

     

     

    此时一个简单的定时任务就完成了

     

    job任务里面,还可以通过JobDataMapjob中传递值

    如新建一个DumbJob.cs任务

    using Quartz;
    
    namespace Quartz001
    {
        public class DumbJob: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.WriteLine("DumbJob的任务实例说:" + jobSays + "值是:" + myFloatValue);
            }
        }
    }

     

    修改Program.cs文件代码

    using System.Threading.Tasks;
    using Quartz;
    using Quartz.Impl;
    
    namespace Quartz001
    {
        class Program
        {
            
            static void Main(string[] args)
            {
                //配置Common.Logging的日志输出为控制台的方式
                Common.Logging.LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter { Level = Common.Logging.LogLevel.Info };
    
                try
                {
                    //通过工厂得到Scheduler的一个实例
                    IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
    
                    //开启
                    scheduler.Start();
    
                    //使用JobBuilder合建一个任务并和我们的HelloJob绑定在一起(注意Job的Key-相当于唯一标识)
                    IJobDetail job = JobBuilder.Create<HelloJob>()
                        .WithIdentity("job1", "group1")
                        .Build(); 
    
                    //任务触发器--StartNow()立即执行,执行间隔10s,一直执行
                    ITrigger trigger = TriggerBuilder.Create()
                        .WithIdentity("trigger1", "group1")
                        .StartNow()
                        .WithSimpleSchedule(x => x.WithIntervalInSeconds(10)
                            .RepeatForever())
                        .Build();                
    
                    IJobDetail dumbJob = JobBuilder.Create<DumbJob>()
                        .WithIdentity("myJob", "dumbGroup")
                        .UsingJobData("jobSays", "我是DumbJob,大家好!")
                        .UsingJobData("myFloatValue", 3.141f)
                        .Build();
                    //还可以使用下面的方式传递数据
                    //JobDataMap map = jobDetail.JobDataMap;
                    //map.Put("jobSays", "我是DumbJob,大家好!");
    
                    ITrigger dumbTrigger = TriggerBuilder.Create()                    
                        .StartNow()
                        .WithSimpleSchedule(x=>x.WithIntervalInSeconds(3).WithRepeatCount(3))   //3秒钟执行一次,执行3次(加上启动的一次,输出会有4次)
                        .Build();
    
                    //告诉Quartz用上面的触发器去定时执行job
                    scheduler.ScheduleJob(job, trigger);
                    scheduler.ScheduleJob(dumbJob, dumbTrigger);
    
                    Thread.Sleep(TimeSpan.FromSeconds(60));
    
                    //关闭定时器
                    scheduler.Shutdown();                
                }
                catch (SchedulerException ex)
                {
                    Console.WriteLine(ex);
                }
    
                Console.WriteLine("按任意键退出!");
                Console.ReadKey();
            }
        }
    }

     

    输出结果:

     

     源码下载

    学习参阅资料:

    http://www.cnblogs.com/lzrabbit/archive/2012/04/13/2447609.html

    http://www.cnblogs.com/Raymond-YYC/p/3975378.html

    http://www.cnblogs.com/monian/p/3822980.html

    http://geekswithblogs.net/TarunArora/archive/2013/01/20/quartz.net-scheduler-exposed-via-a-web-service.aspx

  • 相关阅读:
    按单生产案例
    【转】linux中执行外部命令提示" error while loading shared libraries"时的解决办法
    【转】WARNING! File system needs to be upgraded. You have version null and I want version 7. Run the '${HBASE_HOME}/bin/hbase migrate' script. 的解决办法
    根据Rowkey从HBase中查询数据
    【转】在一个Job中同时写入多个HBase的table
    sqoop 使用
    给VMware下的Linux扩展磁盘空间(以CentOS6.3为例)
    chrome 版本 29.0.1547.76 m 解决打开新标签页后的恶心页面的问题
    tomcat7+jdk的keytool生成证书 配置https
    如何打包和生成你的Android应用程序
  • 原文地址:https://www.cnblogs.com/jancyxue/p/4151502.html
Copyright © 2011-2022 走看看