Getting started with Quartz Job management

Keywords: Java Database

1.Job components

Job is actually composed of three parts:
JobDetail: used to describe what the Job is doing
Class implementing Job: specific
JobDataMap: used to provide parameters for Job

 

JobDataMap can be used in other ways besides usingJobData

 

2.Job concurrency

By default, no matter whether the last task is finished or not, as long as the specified time is up, the next task will start.
Sometimes it will take a long time to do tasks, such as database backup. At this time, it is hoped that the next backup can be started only after the last backup is completed successfully. Even when the specified time is up, it can not be started, because it is likely to cause the database to be locked (several lines backup the database at the same time, causing unexpected confusion).

In this case, add a note to the database backup task:

@DisallowConcurrentExecution

 

 

3.Job anomaly

It's common to have exceptions in a task. There are usually two ways to handle exceptions:
1. When an exception occurs, notify all the dispatchers who manage the Job and stop running it
2. When an exception occurs, modify the parameters and run again immediately

public class ExceptionJob1 implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        int i = 0;
        try {
            //Intentional abnormality
            System.out.println(100/i);
        } catch (Exception e) {
            System.out.println("Something went wrong. Cancel this Job All corresponding schedules");
            JobExecutionException je =new JobExecutionException(e);
            je.setUnscheduleAllTriggers(true);
            throw je;
        }
    }

}
public class ExceptionJob2 implements Job {
    static int i = 0;
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            //Intentional abnormality
            System.out.println("Operation result"+100/i);
        } catch (Exception e) {
            System.out.println("An exception occurred. Modify the parameters and execute again immediately");
            i = 1;
            JobExecutionException je =new JobExecutionException(e);
            je.setRefireImmediately(true);      //Redo job now
            throw je;
        }
    }
}
public class ExceptionTest {
    public static void main(String[] args) throws Exception{
        exceptionHandle1();
        exceptionHandle2();
    }
    private static void exceptionHandle1() throws Exception {
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        Trigger trigger = newTrigger().withIdentity("trigger1", "group1")
                .startNow()
                .withSchedule(simpleSchedule()
                        .withIntervalInSeconds(2)
                        .withRepeatCount(10))
                .build();

        //Define a JobDetail
        JobDetail job = newJob(ExceptionJob1.class)
                .withIdentity("exceptionJob1", "someJobGroup")
                .build();

        //Schedule to join this job
        scheduler.scheduleJob(job, trigger);

        //start-up
        scheduler.start();

        //Wait 20 seconds for the previous tasks to be completed before shutting down the scheduler
        Thread.sleep(20000);
        scheduler.shutdown(true);
    }
private static void exceptionHandle2() throws Exception { Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); Trigger trigger = newTrigger().withIdentity("trigger1", "group1") .startNow() .withSchedule(simpleSchedule() .withIntervalInSeconds(2) .withRepeatCount(10)) .build(); //Define a JobDetail JobDetail job = newJob(ExceptionJob2.class) .withIdentity("exceptionJob1", "someJobGroup") .build(); //Schedule to join this job scheduler.scheduleJob(job, trigger); //start-up scheduler.start(); //Wait 20 seconds for the previous tasks to be completed before shutting down the scheduler Thread.sleep(20000); scheduler.shutdown(true); } }

 

 

 

4. interrupt Job

In business, sometimes tasks need to be interrupted, so this Job needs to implement the InterruptableJob interface, and then it is convenient to interrupt

public class StoppableJob implements InterruptableJob {

    private boolean stop = false;

    @Override
    public void interrupt() throws UnableToInterruptJobException {
        System.out.println("Stopped by the dispatcher");
        stop = true;
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        while(true){

            if(stop)
                break;
            try {
                System.out.println("Check every 1 second to see if it stops");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("On going...");
        }
    }

}

test

public class Stop {
    public static void main(String[] args) throws Exception{
Scheduler scheduler
= StdSchedulerFactory.getDefaultScheduler(); Trigger trigger = newTrigger().withIdentity("trigger1", "group1") .startNow() .build(); //Define a JobDetail JobDetail job = newJob(StoppableJob.class) .withIdentity("exceptionJob1", "someJobGroup") .build(); //Schedule to join this job scheduler.scheduleJob(job, trigger); //start-up scheduler.start(); Thread.sleep(5000); System.out.println("After 5 seconds, scheduling stops job"); //key It's like this Job Primary key scheduler.interrupt(job.getKey()); //Wait 20 seconds for the previous tasks to be completed before shutting down the scheduler Thread.sleep(20000); scheduler.shutdown(true); } }

 

Posted by ethan89 on Tue, 17 Mar 2020 03:53:05 -0700