Two triggers of Quartz (simpletrigger & & crontigger)

1, What is quartz???

Quartz is another open source project of OpenSymphony open source organization in the field of Job scheduling.
It is an open source task schedule management system completely developed by java
In short, it is a system to realize "planned (or scheduled) tasks"

2, quartz official website

quartz official website

If you want to have a deeper understanding of quartz, you can go to its official website. The place framed in the figure below has all the explanations about quartz knowledge

3, Quartz trigger

It has five types of triggers
SimpleTrigger
CronTirgger
DateIntervalTrigger
NthIncludedDayTrigger
Calendar Class (org.quartz.Calendar)

Today we will introduce SimpleTrigger and CronTrigger.

Application scenario:
SimpleTrigger: execute N times and repeat N times
CronTrigger: a few seconds, minutes, hours, days, months, weeks and years

4, Storage mode

RAMJobStore (memory job storage type) and JDBC jobstore (database job storage type)

advantage shortcoming
RAMJobStore No external database, easy configuration and fast running speed Because the scheduler information is stored in the memory allocated to the JVM, all scheduling information will be lost when the application stops running. In addition, because it is stored in the JVM memory, the number of jobs and triggers that can be stored will be limited
JDBCJobStore Clusters are supported because all task information will be saved The speed of running depends on the speed of connecting to the database. Things can be controlled in the database. In addition, if the application server is shut down or restarted, the task information will not be lost, and the tasks that failed due to the server shutdown or restart can be recovered

Operating principle

5, Generate expression URL Online

Generate expression URL Online


The following figure shows the commonly used dates

6, quartz trigger case

1. Create a project

2. Import jar package

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


3. Create two classes to test the function of this world trigger

package com.zking.quartz01.job;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * @author Xiao Qi
 * @create  2020-12-03 11:16
 */
public class RamJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("Business logic code for specific execution of scheduled tasks...");

    }
}

Case 1: introduction trigger case

package com.zking.quartz01.quartz;

import com.zking.quartz01.job.RamJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import static org.quartz.JobBuilder.newJob;

/**
 * @author Xiao Qi
 * @create  2020-12-03 11:07
 */
public class Demo1 {
    public static void main(String[] args) throws Exception{
        //Scheduler
        SchedulerFactory schedulerFactory=new StdSchedulerFactory();
        Scheduler scheduler=schedulerFactory.getScheduler();
        //class
        JobDetail jobDetail=newJob(RamJob.class)
                .withIdentity("job1","group1")
                .withDescription("this is job1")
                .build();

        //trigger
        Trigger trigger =(Trigger) TriggerBuilder.newTrigger()
//        It is executed 3 times in total and every 6 seconds
            .withSchedule(SimpleScheduleBuilder.repeatSecondlyForTotalCount(3,6))
            .withIdentity("trigger1","group1")
            .withDescription("this is trigger1")
            .build();
        //Scheduler assembly class and trigger
        scheduler.scheduleJob(jobDetail,trigger);
        scheduler.start();
    }
}

Run test

Case 2: timed and fixed-point execution of expression trigger

package com.zking.quartz01.quartz;

import com.zking.quartz01.job.RamJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import static org.quartz.JobBuilder.newJob;

/**
 * @author Xiao Qi
 * @create  2020-12-03 11:07
 *
 * Expression trigger
 *
 * Timing and fixed-point execution
 *
 */
public class Demo2 {
    public static void main(String[] args) throws Exception{
        //Scheduler
        SchedulerFactory schedulerFactory=new StdSchedulerFactory();
        Scheduler scheduler=schedulerFactory.getScheduler();
        //class
        JobDetail jobDetail=newJob(RamJob.class)
                .withIdentity("job1","group1")
                .withDescription("this is job1")
                .build();

        //trigger
        Trigger trigger =(Trigger) TriggerBuilder.newTrigger()
            .withSchedule(CronScheduleBuilder.cronSchedule("0 56 18 * * ?"))
            .withIdentity("trigger1","group1")
            .withDescription("this is trigger1")
            .build();
        //Scheduler assembly class and trigger
        scheduler.scheduleJob(jobDetail,trigger);
        scheduler.start();
    }
}


Operation results

Case 3: the expression trigger case follows a certain law and executes circularly, unlimited times

package com.zking.quartz01.quartz;

import com.zking.quartz01.job.RamJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import static org.quartz.JobBuilder.newJob;

/**
 * @author Xiao Qi
 * @create  2020-12-03 11:07
 *
 * Expression trigger
 *
 * Follow a certain rule and execute in cycles, unlimited times
 *
 */
public class Demo3 {
    public static void main(String[] args) throws Exception{
        //Scheduler
        SchedulerFactory schedulerFactory=new StdSchedulerFactory();
        Scheduler scheduler=schedulerFactory.getScheduler();
        //class
        JobDetail jobDetail=newJob(RamJob.class)
                .withIdentity("job1","group1")
                .withDescription("this is job1")
                .build();

        //trigger
        Trigger trigger =(Trigger) TriggerBuilder.newTrigger()
            //Every ten seconds
            .withSchedule(CronScheduleBuilder.cronSchedule("0/10 * * * * ?"))
            .withIdentity("trigger1","group1")
            .withDescription("this is trigger1")
            .build();
        //Scheduler assembly class and trigger
        scheduler.scheduleJob(jobDetail,trigger);
        scheduler.start();
    }
}


Operation results

Case 4: timing task parameter transfer problem

package com.zking.quartz01.job;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * @author Xiao Qi
 * @create  2020-12-03 11:16
 */
public class RamJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("Business logic code for specific execution of scheduled tasks...");
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        System.out.println(jobDataMap.get("name").toString() + ":" + jobDataMap.get("level").toString() + ":" + jobDataMap.get("job").toString());
    }
}

package com.zking.quartz01.quartz;

import com.zking.quartz01.job.RamJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import static org.quartz.JobBuilder.newJob;

/**
 * @author Xiao Qi
 * @create  2020-12-03 11:07
 *
 *Timing task parameter transfer problem
 */
public class Demo4 {
    public static void main(String[] args) throws Exception{
        //Scheduler
        SchedulerFactory schedulerFactory=new StdSchedulerFactory();
        Scheduler scheduler=schedulerFactory.getScheduler();
        //class
        JobDetail jobDetail=newJob(RamJob.class)
                .withIdentity("job1","group1")
                .withDescription("this is job1")
                .build();
        JobDataMap jobDataMap =jobDetail.getJobDataMap();
        jobDataMap.put("name","Xiao Qi");
        jobDataMap.put("level","lovely");
        jobDataMap.put("job","student");

        //trigger
        Trigger trigger =(Trigger) TriggerBuilder.newTrigger()
            //Every ten seconds
            .withSchedule(CronScheduleBuilder.cronSchedule("0/10 * * * * ?"))
            .withIdentity("trigger1","group1")
            .withDescription("this is trigger1")
            .build();
        //Scheduler assembly class and trigger
        scheduler.scheduleJob(jobDetail,trigger);
        scheduler.start();
    }
}


Operation results

7, SpringTask time controller case

package com.zking.quartz01.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author Xiao Qi
 * @create  2020-12-03 19:18
 */
@Component
public class SpringTask {
    @Scheduled(cron = "0/10 * * * * ?")
    public void xiaoqi(){
        System.out.println("spring Timed tasks built into the framework.....");
    }
}


Run in Quartz01Application

Operation results

8, Advantages and disadvantages of Spring task and Quartz

advantage shortcoming
Spring task Without integrating spring, the business service can be called in the job class Single thread; You cannot perform scheduled tasks of data storage type
Quartz Multithreading; It can do data storage type scheduled tasks with high maintainability; spring needs to be integrated, and business layer service s cannot be called directly;

9, Spring task single thread and quartz multithreading cases

springtask single thread

Operation results

quartz multithreading case

package com.zking.quartz01.job;

        import org.quartz.Job;
        import org.quartz.JobDataMap;
        import org.quartz.JobExecutionContext;
        import org.quartz.JobExecutionException;

        import java.text.SimpleDateFormat;
        import java.util.Date;

/**
 * @author Xiao Qi
 * @create  2020-12-03 11:16
 */
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())+" : be based on RAM of quartz Scheduling framework scheduled tasks...");

        try {
            Thread.sleep(20*1000);
            System.out.println("Simulation is processing big data....");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

package com.zking.quartz01.quartz;

import com.zking.quartz01.job.RamJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import static org.quartz.JobBuilder.newJob;

/**
 * @author Xiao Qi
 * @create  2020-12-03 20:06
 */
public class Demo5 {
    public static void main(String[] args) throws SchedulerException {
        SchedulerFactory factory = new StdSchedulerFactory();
//        Scheduler creation
        Scheduler scheduler = factory.getScheduler();

//        Code to be executed for specific scheduled tasks
        JobDetail jobDetail = newJob(RamJob.class)
                .withIdentity("job2", "group1")
                .withIdentity("This is an operation case")
                .build();

        Trigger trigger = (Trigger) TriggerBuilder.newTrigger()
//                Every 10s
                .withSchedule(CronScheduleBuilder.cronSchedule("0/10 * * * * ?"))
//                Trigger ID
                .withIdentity("trigger2", "group1")
                .withDescription("This is a trigger")
                .build();

//       Scheduling factory binding job class and trigger
        scheduler.scheduleJob(jobDetail, trigger);
        scheduler.start();
    }
}

Operation results


Bugs encountered


resolvent
Go to pom and delete all jar s about the database

Tags: Quartz

Posted by Alffallen on Wed, 04 May 2022 09:07:00 +0300