• quartz入门


    1、Quartz简介及应用场景

    2、Quartz简单触发器 SimpleTrigger介绍

    3、Quartz表达式触发器CronTirgger介绍

    4、Quartz中参数传递

    5、Spring task Vs Quartz

    Quartz简介及应用场景

    1. Quartz介绍

       任务调度框架“Quartz”是OpenSymphony开源组织在Job scheduling领域又一个开源项目,是完全由java开发的一个开源的任务日程管理系统,

       “任务进度管理器”就是一个在预先确定(被纳入日程)的时间到达时,负责执行(或者通知)其他软件组件的系统。

       

       简单来说就是实现“计划(或定时)任务”的系统,例如:订单下单后未付款,15分钟后自动撤消订单,并自动解锁锁定的商品

    2. Quartz的触发器

       触发器用来告诉调度程序作业什么时候触发。框架提供了5种触发器类型,但两个最常用的SimpleTrigger和CronTrigger。

       五种类型的Trigger(定时器)

       SimpleTrigger,CronTirgger,DateIntervalTrigger,NthIncludedDayTrigger和Calendar类( org.quartz.Calendar)。

       场景:

       SimpleTrigger:执行N次,重复N次

       CronTrigger:几秒 几分 几时 哪日 哪月 哪周 哪年,执行

    3. 存储方式

       RAMJobStore(内存作业存储类型)和JDBCJobStore(数据库作业存储类型),两种方式对比如下:

      

                    优点                                    缺点

       RAMJobStore  不要外部数据库,配置容易,运行速度快    因为调度程序信息是存储在被分配给JVM的内存里面,

                                                            所以,当应用程序停止运行时,所有调度信息将被丢失。

                                                            另外因为存储到JVM内存里面,所以可以存储多少个Job和Trigger将会受到限制

       JDBCJobStor  支持集群,因为所有的任务信息都会保存    运行速度的快慢取决与连接数据库的快慢

                    到数据库中,可以控制事物,还有就是如

                    果应用服务器关闭或者重启,任务信息都

                    不会丢失,并且可以恢复因服务器关闭或

                    者重启而导致执行失败的任务   

     

    图解quartz工作流程

    quartz相关表达式

    在线生成表达式网址:http://cron.qqe2.com/

    所需pom依赖

    <dependency>
               <groupId>org.quartz-scheduler</groupId>
               <artifactId>quartz</artifactId>
               <version>2.2.1</version>
          </dependency>
          <dependency>
               <groupId>org.quartz-scheduler</groupId>
               <artifactId>quartz-jobs</artifactId>
               <version>2.2.1</version>
          </dependency>

    Quartz简单触发器 SimpleTrigger介绍

    每次执行 * 长时间,每次间隔 * 长时间

    先创建一个实例

     

    package com.hmc.quzrtzs.job;
    
    import org.quartz.*;
    
    /**
     * @author胡明财
     * @site www.xiaomage.com
     * @company xxx公司
     * @create  2019-11-28 22:16
     */
    public class MyJob implements Job{
    
        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            System.out.println("这是一个简单的任务");
    
    //        JobDetail JobDetail=jobExecutionContext.getJobDetail();
    //        JobDataMap JobDataMap=JobDetail.getJobDataMap();
    //        System.out.println("name="+JobDataMap.get("name")+",age="+JobDataMap.get("age"));
        }
    
    }

     

     

     2、Quartz简单触发器 SimpleTrigger介绍

    package com.hmc.quzrtzs.quartz;
    
    import com.hmc.quzrtzs.job.MyJob;
    import org.quartz.*;
    import org.quartz.impl.StdSchedulerFactory;
    
    import java.util.Date;
    
    import static org.quartz.JobBuilder.newJob;
    
    /**
     * @author胡明财
     * @site www.xiaomage.com
     * @company xxx公司
     * @create  2019-12-01 19:35
     */
    public class demo1 {
        public static void main(String[] args) throws SchedulerException {
            try {
                //1.创建ShedulerFactor工厂类
                SchedulerFactory schedulerFactory=new StdSchedulerFactory();
                //2.获取Scheduler调度实例
                Scheduler scheduler = schedulerFactory.getScheduler();
                //3 创建JobDetail
                //jobname+jobgroup=primary key identity(唯一标识)
                JobDetail jobDetail=newJob(MyJob.class)
                        .withDescription("this is a jobDetail!!!")
                        .withIdentity("jobname1","jobgroup1")
                        .build();
                //4.创建Trigger(SimpleTrigger和CronTrigger)
                // SimpleTrigger:执行N次,重复N次
                // CronTrigger:几秒 几分 几时 哪日 哪月 哪周 哪年,执行
                //触发器
                Trigger trigger=TriggerBuilder.newTrigger()
                        .withDescription("this is a jobDetail!!!")
                        .withIdentity("jobname1","jobgroup1")
                         .withSchedule(SimpleScheduleBuilder.repeatSecondlyForTotalCount(3,6
                         ))
    
                        .build();
                //5.将JobDetail和Trgger注入到Scheduler调度器中
                scheduler.scheduleJob(jobDetail,trigger);
                //6 启动任务
                scheduler.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    }

     

     

    3、Quartz表达式触发器CronTirgger介绍

    package com.hmc.quzrtzs.quartz;
    
    import com.hmc.quzrtzs.job.MyJob;
    import org.quartz.*;
    import org.quartz.impl.StdSchedulerFactory;
    
    import static org.quartz.JobBuilder.newJob;
    
    /**
     * @author胡明财
     * @site www.xiaomage.com
     * @company xxx公司
     * @create  2019-12-01 19:35
     * 表达式触发器
     */
    public class demo2 {
        public static void main(String[] args) throws SchedulerException {
            try {
                //1.创建ShedulerFactor工厂类
                SchedulerFactory schedulerFactory=new StdSchedulerFactory();
                //2.获取Scheduler调度实例
                Scheduler scheduler = schedulerFactory.getScheduler();
                //3 创建JobDetail
                //jobname+jobgroup=primary key identity(唯一标识)
                JobDetail jobDetail=newJob(MyJob.class)
                        .withDescription("this is a jobDetail!!!")
                        .withIdentity("jobname1","jobgroup1")
                        .build();
                //4.创建Trigger(SimpleTrigger和CronTrigger)
                // SimpleTrigger:执行N次,重复N次
                // CronTrigger:几秒 几分 几时 哪日 哪月 哪周 哪年,执行
                //触发器
                Trigger trigger=TriggerBuilder.newTrigger()
                        .withDescription("this is a jobDetail!!!")
                        .withIdentity("jobname1","jobgroup1")
                        .withSchedule(CronScheduleBuilder.cronSchedule("*/5 * * * * ? "))
                        .build();
                //5.将JobDetail和Trgger注入到Scheduler调度器中
                scheduler.scheduleJob(jobDetail,trigger);
                //6 启动任务
                scheduler.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    }

     每10秒执行一次

     

     4、Quartz中参数传递

    package com.hmc.quzrtzs.quartz;
    
    import com.hmc.quzrtzs.job.MyJob;
    import org.quartz.*;
    import org.quartz.impl.StdSchedulerFactory;
    
    import static org.quartz.JobBuilder.newJob;
    
    /**
     * @author胡明财
     * @site www.xiaomage.com
     * @company xxx公司
     * @create  2019-12-01 19:35
     * 参数传递
     */
    public class demo3 {
        public static void main(String[] args) throws SchedulerException {
            try {
                //1.创建ShedulerFactor工厂类
                SchedulerFactory schedulerFactory=new StdSchedulerFactory();
                //2.获取Scheduler调度实例
                Scheduler scheduler = schedulerFactory.getScheduler();
                //3 创建JobDetail
                //jobname+jobgroup=primary key identity(唯一标识)
                JobDetail jobDetail=newJob(MyJob.class)
                        .withDescription("this is a jobDetail!!!")
                        .withIdentity("jobname1","jobgroup1")
                        .build();
                //参数传递
                JobDataMap JobDataMap=jobDetail.getJobDataMap();
                JobDataMap.put("name","胡明财");
                JobDataMap.put("age",19);
                //4.创建Trigger(SimpleTrigger和CronTrigger)
                // SimpleTrigger:执行N次,重复N次
                // CronTrigger:几秒 几分 几时 哪日 哪月 哪周 哪年,执行
                //触发器
                Trigger trigger=TriggerBuilder.newTrigger()
                        .withDescription("this is a jobDetail!!!")
                        .withIdentity("jobname1","jobgroup1")
                        .withSchedule(CronScheduleBuilder.cronSchedule("*/5 * * * * ? "))
                        .build();
                //5.将JobDetail和Trgger注入到Scheduler调度器中
                scheduler.scheduleJob(jobDetail,trigger);
                //6 启动任务
                scheduler.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    }

     任务实例

    package com.hmc.quzrtzs.job;
    
    import org.quartz.*;
    
    /**
     * @author胡明财
     * @site www.xiaomage.com
     * @company xxx公司
     * @create  2019-11-28 22:16
     */
    public class MyJob implements Job{
    
        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            System.out.println("这是一个简单的任务");
    
            JobDetail JobDetail=jobExecutionContext.getJobDetail();
            JobDataMap JobDataMap=JobDetail.getJobDataMap();
            System.out.println("name="+JobDataMap.get("name")+",age="+JobDataMap.get("age"));
        }
    
    }

     

    5、Spring task Vs Quartz

    Spring task

    优点:无需整合spring,作业类中就可以调用业务service

    缺点:单线程;不能做数据存储型的定时任务

     

    Quartz

    优点:多线程;可以做数据存储型的定时任务,维护性高;

    缺点:需要整合spring,不能直接调用业务层service

     

     

    线程论证代码

    package com.hmc.quzrtzs.task;
    
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    /**
     * @author胡明财
     * @site www.xiaomage.com
     * @company xxx公司
     * @create  2019-12-01 19:50
     */
    @Component
    public class SpringTask {
    
        @Scheduled(cron = "0/10 * * * * ?")
        public void xxx(){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.err.println(format.format(new Date())+" : 这是一个spring task...");
    
            try {
                Thread.sleep(20*1000);
                System.out.println("模拟正在处理大数据....");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
    
    
    }
    QuzrtzsApplication
    package com.hmc.quzrtzs;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.scheduling.annotation.EnableScheduling;
    
    @EnableScheduling
    @SpringBootApplication
    public class QuzrtzsApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(QuzrtzsApplication.class, args);
        }
    
    }

     

    结果是spring task中的定时任务变成了30s执行一次

    Quartz代码

    package com.hmc.quzrtzs.quartz;
    
    import com.hmc.quzrtzs.job.MyJob;
    import com.hmc.quzrtzs.job.RamJob;
    import org.quartz.*;
    import org.quartz.impl.StdSchedulerFactory;
    
    import static org.quartz.JobBuilder.newJob;
    
    /**
     * @author胡明财
     * @site www.xiaomage.com
     * @company xxx公司
     * @create  2019-12-01 20:00
     */
    public class demo4 {
        public static void main(String[] args) throws SchedulerException {
            SchedulerFactory factory = new StdSchedulerFactory();
    //        调度器创建
            Scheduler scheduler = factory.getScheduler();
    
    //        具体定时任务需要执行的代码
            JobDetail jobDetail = newJob(RamJob.class)
                    .withIdentity("job2", "group1")
                    .withIdentity("这是一个作业类案例")
                    .build();
    
            Trigger trigger = (Trigger) TriggerBuilder.newTrigger()
    //                每10s执行一次
                    .withSchedule(CronScheduleBuilder.cronSchedule("0/10 * * * * ?"))
    //                触发器标识
                    .withIdentity("trigger2", "group1")
                    .withDescription("这是一个触发器")
                    .build();
    
    //       调度工厂绑定作业类及触发器
            scheduler.scheduleJob(jobDetail, trigger);
            scheduler.start();
        }
    }
    RamJob
    package com.hmc.quzrtzs.job;
    
    import org.quartz.Job;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    /**
     * @author胡明财
     * @site www.xiaomage.com
     * @company xxx公司
     * @create  2019-12-01 20:06
     */
    public class RamJob implements Job {
        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.err.println(format.format(new Date())+" : 基于RAM的quartz调度框架定时任务...");
    
            try {
                Thread.sleep(20*1000);
                System.out.println("模拟正在处理大数据....");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    

    结果:不管前一个定时任务的线程是否结束,都会开启下一个线程,依然每10s执行一次;

    效果图如下:

     
  • 相关阅读:
    Week2实验 B--爆零(❌)大力出奇迹(√) HDU
    Windows10家庭版安装Docker(不是DockerToolbox)
    Ubuntu搭建DNS服务器遇到的问题1
    Ubuntu执行apt-get时遇到的问题1
    Windows2000下vc++6.0编译出现“Error spawning cl.exe”
    win2000安装官方发布的最后一个补丁KB891861
    Windows2000密钥
    Linux下使用gets和puts方法出现的错误
    执行.sh文件调用变量时出现“未找到命令”
    SQL Server2012无法连接到服务器
  • 原文地址:https://www.cnblogs.com/xmf3628/p/11967477.html
Copyright © 2020-2023  润新知