Quartz entry and related expressions using

purpose:

  1, the Quartz introduction and application scenarios

  2, the Quartz simple trigger  SimpleTrigger introduction

  3, the Quartz expression trigger CronTirgger Introduction

  . 4, the Quartz parameters passed

  5、Spring task Vs Quartz


Quartz introduction and application scenarios

  •  Quartz Introduction

Task scheduling framework "Quartz" is OpenSymphony open-source organization has an open source project in the field of Job scheduling is an open source job scheduling system developed entirely by java,

When the "Task Manager progress" is in a pre-determined (to be included in the agenda) time to reach, is responsible for the implementation of the system (or notice) other software components.

   

In short, to achieve "plan (or timing) mission," the system, such as: non-payment orders after the orders, the order is automatically revoked after 15 minutes and automatically unlock a locked merchandise

  •  Quartz trigger 

  Triggers used to tell the dispatcher job when triggered. Framework provides five kinds of trigger types, but the two most common and SimpleTrigger CronTrigger.

   Five types of Trigger (Timer)

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

 

   Scenes:

   SimpleTrigger: performing N times, is repeated N times

   CronTrigger: a few seconds when a fraction of what day of what month which weeks which, execution

  •  Storage

    The RAMJobStore (memory storage type job) and JDBCJobStore (database storage type job), comparison of two ways as follows:

  1. advantages  :

RAMJobStore   not external database, easy to configure, run fast because the scheduler information is stored in the memory is allocated to the JVM inside, so when the application is stopped, all scheduling information will be lost. 
Moreover, because the JVM memory to store inside, so you can store the number of Job and Trigger will be limited

  2. Disadvantages:

JDBCJobStor   clustered, because the speed depends on connection speed database of all the tasks running speed information will be saved 
to the database, you can control things, there is as                 if the application server is shut down or restart, the task information is                 not lost and can be restored because server is down or                 who caused restart the task execution failure 

quartz workflow diagram below:

 

(Generated online expression web site: http://cron.qqe2.com/ )

  quartz related expression

Sub-expressions:

position significance Valid values Available special characters
1 Seconds 0-59 , - * /
2 Minutes 0-59 , - * /
3 Hours 0 - 23 , - * /
4 Day-of-Month 1--31 (note that some special month) , - * / ? L W
5 Month 0--11  or  the string "JAN, FEB, the MAR, the APR,  MAY, JUN, JUL, the AUG, the SEP, the OCT, NOV DEC" , - * /
6 Week-of-Day (Weekly) 1--7  or  the string "SUN, MON, TUE, WED, THU,  FRI, SAT" represents  *  Note: 1 == SUN , - * / ? L #
7 Year (in optional fields) empty or 1970-2099 , - * /

 

 

Special characters :

 

symbol Show for example
/ each Expressions used in conjunction with the current sub occupy a position subexpression  Example: "3/15" on the second subexpression bit, begin a third minutes, every 15 minutes
? One day There is only of-Week Day-use and Day-of-Month and to resolve the two conflicts in which the expression of a child under the expression has the value of the case? Written on another expression means match any value so we will not use * to match any value to represent the  cases: monthly 4:00 am No. 15: "00415 *?"  every Friday at 23:00: "? 0 0 23 * FRI "
L Monthly or weekly last day 只存在与 Day-of-Month 和 Day-of-Week 中使用, 在 Day-of-Month 子表达式中,“L”表示一个月的最后一天 在 Day-of-Week 子表达式中,“L”表示一个星期的最后一天,也就是SAT 例: “0 15 10 ? * 6L” 表示 每月最后一个星期五10:15分运行。 "0 15 10 2L * ?" 表示 每月倒数第二天10:15分运行。
W 最近工作日 只存在与 Day-of-Month 最近的工作日: 例: "0 15 10 15W * ?" 每个月距离15日最近的工作日 如 15日是周六则执行时间是14日 若15日是周日 则执行时间是16 如15号是工作日就15执行 就近匹配不会跨出当前月
# 第几个星期几 只存在与 Day-of-Week 中 每月第n个工作日 例:“0 15 10 ? * 6#3” 表示每个月第三个星期五 “0 15 10 ? * 4#2” 表示每个月第二个星期三
, 多个 例: "0 0 0,13,18,21 * * ?": 每天的0点、13点、18点、21点都执行一次:
- 区间 例: "0 0-5 14 * * ?" : 在每天下午2点到下午2:05期间的每1分钟触发
* 补位符 补位 但是 注意: Day-of-Month 和 Day-of-Week 肯定有一个为 ? 也不能两个 ?

 

 

首先新建一个项目并且选择我们需要用的一些常见jar包

  

   在新项目pom中导入quartz所需要的依赖

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
        </dependency>
        <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定时任务业务内容的类 RamJob

 

package com.ting.quartz01.job;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
 * @author 黄大娘
 * @company dogsun公司
 * @create 2019-11-14 19:11
 *
 * 基于内存RAM
 */
public class RamJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException{
        //此处为quartz定时任务执行的业务内容
        System.out.println("常记溪亭日暮,沉醉不知归路");
    }
}

 


Quartz简单触发器 SimpleTrigger

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

   Dome1.java

package com.ting.quartz01.demo;
import com.ting.quartz01.job.RamJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import static org.quartz.JobBuilder.newJob;
/**
 * @author 黄大娘
 * @company dogsun公司
 * @create 2019-11-14 19:15
 *
 * 讲解简单触发器(每个N秒执行,一共执行多少次)
 */
public class Demo1 {
    public static void main(String[] args) throws SchedulerException {
//        schedule、jobDetail、trigger
        SchedulerFactory factory = new StdSchedulerFactory();
        Scheduler scheduler = factory.getScheduler();

        JobDetail jobDetail= newJob(RamJob.class)
                .withIdentity("job1","group1")
                .withDescription("这是第一quartz定时任务")
                .build();
        Trigger trigger =(Trigger)TriggerBuilder.newTrigger()
                .withSchedule(SimpleScheduleBuilder.repeatSecondlyForTotalCount(3,6))
                .withIdentity("triggerl","group1")
                .withDescription("一个触发器")
                .build();
scheduler.scheduleJob(jobDetail,trigger); scheduler.start(); } }

效果:

 


Quartz表达式触发器

   Demo2.java

package com.ting.quartz01.demo;
import com.ting.quartz01.job.RamJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import static org.quartz.JobBuilder.newJob;

/**
 * @author 黄大娘
 * @company dogsun公司
 * @create 2019-11-14 19:15
 *
 * 讲解表达式触发器(可以定时定点无线循环代码路径)
 */
public class Demo2 {
    public static void main(String[] args) throws SchedulerException {
//        schedule、jobDetail、trigger
        SchedulerFactory factory = new StdSchedulerFactory();
        Scheduler scheduler = factory.getScheduler();

        JobDetail jobDetail= newJob(RamJob.class).withIdentity("job2","group2").withDescription("这是quartz定时任务").build();
        Trigger trigger =(Trigger)TriggerBuilder.newTrigger()
                //定点执行逻辑
                //.withSchedule(CronScheduleBuilder.cronSchedule("0 45 14 * * ?"))
                //每六秒循环执行
                .withSchedule(CronScheduleBuilder.cronSchedule("0/3 * * * * ?"))
                .withIdentity("trigger2","group2")
                .withDescription("this is a trigger")
                .build();
scheduler.scheduleJob(jobDetail,trigger); scheduler.start(); } }

 

效果:

 

 

 

 


Quartz中参数传递

   给执行类中添加参数,并且给它定时三秒

  

package com.ting.quartz01.demo;
import com.ting.quartz01.job.RamJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import static org.quartz.JobBuilder.newJob;
public class Demo3 {
    public static void main(String[] args) throws SchedulerException {
//        schedule、jobDetail、trigger
        SchedulerFactory factory = new StdSchedulerFactory();
        Scheduler scheduler = factory.getScheduler();

        JobDetail jobDetail= newJob(RamJob.class)
                .withIdentity("job3","group3")
                .withDescription("这是一个quartz定时任务").build();

        String name = "大娘";
        String sex = "女";
        String aihao = "古乐";
        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        jobDataMap.put("name",name);
        jobDataMap.put("sex",sex);
        jobDataMap.put("aihao",aihao);

        Trigger trigger =(Trigger)TriggerBuilder.newTrigger()
                //定点执行逻辑
                //.withSchedule(CronScheduleBuilder.cronSchedule("0 45 14 * * ?"))
                //每六秒循环执行
                .withSchedule(CronScheduleBuilder.cronSchedule("0/3 * * * * ?"))
                .withIdentity("trigger2","group2")
                .withDescription("this is a trigger")
                .build();

        scheduler.scheduleJob(jobDetail,trigger);
        scheduler.start();
    }
}

  我们还要去定时执行任务内容的类中接收并且输出自定义的参数

  RamJob

public class RamJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException{
        //此处为quartz定时任务执行的业务内容
        //System.out.println("常记溪亭日暮,沉醉不知归路");
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        System.out.println(jobDataMap.get("name"));
        System.out.println(jobDataMap.get("sex"));
        System.out.println(jobDataMap.get("aihao"));
    }
}

效果:

  每三秒执行一次自定义的参数内容

 


Spring task Vs Quartz

  •  Spring task

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

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

  • Quartz

    优点:多线程;可以做数据存储型的定时任务,维护性高;
    缺点:需要整合spring,不能直接调用业务层service;

在执行代码前记得在启动类中加一个 事务注解 

  

单线程:

  点击启动类启动,就会每隔十秒执行一次语句

SpringTask 类
@Component//主键
public class SpringTask {
    @Scheduled(cron = "1/10 * * * * ?")
    public void xxx(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.err.println("Spring task启动"+ format.format(new Date()));
    }
}

效果:

在类中添加一段代码:

@Component//主键
public class SpringTask {
    @Scheduled(cron = "1/10 * * * * ?")
    public void xxx(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.err.println("Spring task启动"+ format.format(new Date()));
        try {
            Thread.sleep(20*1000);
            System.out.println( "模拟正在处理大数据,,,,");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

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

 

多线程

 Dome4

package com.ting.quartz01.demo;
import com.ting.quartz01.job.RamJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import static org.quartz.JobBuilder.newJob;
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","group2")
                .withDescription("这是quartz定时任务")
                .build();

        Trigger trigger = (Trigger)TriggerBuilder.newTrigger()
                .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
                .withIdentity("trigger2","group2")
                .withDescription("this is a trigger")
                .build();

        scheduler.scheduleJob(jobDetail,trigger);
        scheduler.start();
    }
}

RamJob

public class RamJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //此处为quartz定时任务执行的业务内容
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.err.println("quartz task..."+format.format(new Date()));
            try {
                Thread.sleep(20*1000);
                System.out.println("模拟处理大数据量");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }
}

效果:

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

 

 

 

 

谢谢观看!

Guess you like

Origin www.cnblogs.com/huangting/p/11858701.html