quartz2.3.0 (5) to formulate strategies to miss misfire mission

Thank Xiongtai: " the Quartz-Misfire missed, compensation execution "

misfire defined

 misfire: missed tasks strategy

misfire reproduce --CronTrigger

job task categories:

Package org.quartz.examples.example5; 

Import org.quartz.DisallowConcurrentExecution;
 Import the org.quartz.Job;
 Import org.quartz.JobDataMap;
 Import org.quartz.JobExecutionContext;
 Import org.quartz.JobExecutionException;
 Import org.quartz.PersistJobDataAfterExecution ; 

Import the java.text.SimpleDateFormat;
 Import java.util.Date; 

/ ** 
 * <pre> 
 * task job. 
 * Because @DisallowConcurrentExecution notes, so the job can not be performed simultaneously trigger multiple timers or otherwise misfire will trigger the timer, we need to define a good timer misfire strategy. 
 * If you do not define a misfire, there will be 
 * </ pre> 
 * / 
@PersistJobDataAfterExecution  // persistent JobDataMap in the data, so that the next regular tasks can get these values 
@DisallowConcurrentExecution   // prohibiting concurrent multi-tasking, it is always only one task to perform in 
public  class StatefulDumbJob the implements the Job { 

    // task execution counter 
    public  static  Final String NUM_EXECUTIONS = "NumExecutions" ;
     public  static  Final String EXECUTION_DELAY = "ExecutionDelay" ;
     public  static  Final the SimpleDateFormat of SDF = new new the SimpleDateFormat ( "the mM-dd-YYYY HH: mm: ss.SSS" ); 

    // must be public no argument constructor modified 
    public StatefulDumbJob () { 
    }

    //定时器执行方法
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("---" + context.getJobDetail().getKey() + " executing.   [" + SDF.format(new Date()) + "]");
        //获得带状态集合
        JobDataMap map = context.getJobDetail().getJobDataMap();

        int executeCount = 0;
        if (map.containsKey(NUM_EXECUTIONS)) {
            executeCount = map.getInt(NUM_EXECUTIONS);
        }

        executeCount++;

        map.put(NUM_EXECUTIONS, executeCount);

        System.out.println("  -" + context.getJobDetail().getKey() + " complete (" + executeCount + ").[" + SDF.format(new Date())+ "]");

    }

}

Timer categories:

package org.quartz.examples.example5;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.DateBuilder.nextGivenSecondDate;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.Date;

import org.quartz.CronExpression;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdScheduler;
importorg.quartz.impl.StdSchedulerFactory;
 Import org.slf4j.Logger;
 Import org.slf4j.LoggerFactory; 

/ ** 
 * <pre> 
Such demonstrates how to define a strategy misfire timer. misfire: missed mission policy 
 * </ pre> 
 * / 
public  class MisfireExample_CronScheduleBuilder {
     static  Final Logger LoggerFactory.getLogger the LOG = (. MisfireExample_CronScheduleBuilder class ); 

    public  static  void main (String [] args) throws Exception {
         // Initialize a factory scheduling, a scheduling class and instantiate 
        the SchedulerFactory SF = new new the StdSchedulerFactory ();
 //                        Sched = sf.getScheduler Scheduler (); 
        StdScheduler sched = (StdScheduler) sf.getScheduler (); 

        // first parameter: Default is null current time, the time may be specified
         // second parameter of: one minute at 10 divided, that is equal parts 60/10.
        // Example: the current time is 10:26:04, then startTime is 10:30:00. The current time is 10:38:31, then startTime is 10:40:00. 
        NextGivenSecondDate the startTime = DATE ( null , 10 ); 
        the JobDetail Job = newJob (. StatefulDumbJob class ) .withIdentity ( "the jobs that job1", "named group1" )
 //                                 .usingJobData (StatefulDumbJob.EXECUTION_DELAY, 30000L) 
                .build (); 
        String the cron= "0/2 * * * *?"; // every 2 seconds 

        CronScheduleBuilder cronScheduleBuilder = cronSchedule ( new new cronExpression (cron)); 

        // ================= ================================================== ===== 
        // ======================== Misfire definition, start =============== ======== 
        // ======================================== ================================ 

        / * 
         set misfire strategy: CronTrigger.MISFIRE_INSTRUCTION_DO_NOTHING = 2 
         - without triggering immediate implementation 
         - - waiting for the next trigger frequency Cron arrival time sequentially executed in Cron frequency 
         * / 
        cronScheduleBuilder.withMisfireHandlingInstructionDoNothing (); 

        / *
         Set misfire Policy: Trigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY = -1 
         - immediately to miss the first time you begin a frequency - the frequency redo all the missed period - the next time the trigger time after the occurrence frequency greater than the current time, in accordance with the order of execution Interval the remaining frequency 
         - total execution time RepeatCount + 1 
         * / 
//         cronScheduleBuilder.withMisfireHandlingInstructionIgnoreMisfires (); 

        / * 
         * set misfire strategy: CronTrigger.MISFIRE_INSTRUCTION_FIRE_ONCE_NOW = 1 
         * to the current time as the trigger frequency immediately trigger the first execution, and follow Cron frequency followed by the implementation 
         * / 
//         cronScheduleBuilder.withMisfireHandlingInstructionFireAndProceed (); 

        // ==================================== ==================================== 
        // ============ ============ misfire definition, end =======================
        // ================================================ ========================
 
        CronTrigger the Trigger = newTrigger (). withIdentity ( "trigger1", "named group1" ) .startAt (the startTime) 
                .withSchedule (cronScheduleBuilder). Build (); 

        // CronTrigger default misfire strategy is: org.quartz.Trigger.MISFIRE_INSTRUCTION_SMART_POLICY = 0 
        int misfireInstruction = trigger.getMisfireInstruction (); 
        log.info ( "misfire current strategy:" + misfireInstruction); 

        a Date ft = sched.scheduleJob (the job, the Trigger); 
        log.info (job.getKey () toString ().); 

        sched.start (); 
        log.info ( "scheduler starts, the main thread to sleep for 15 seconds !!!! task scheduler thread continue. " ); 
        Thread.sleep ( 15L * 1000L ); 

//         // pause trigger
 //         sched.pauseTrigger (trigger.getKey ());
 //         // continue to trigger
 //         sched.resumeTrigger (trigger.getKey ()); 

        / / suspended task 
        sched.pauseJob (job.getKey ()); 
        log.info ( "scheduler suspend timer, the main thread to sleep for 11 seconds !!!! miss the timing of tasks performed N times job1 simulation when the timer. thread of execution due grab CPU time or other events implementation of miss. " ); 
        Thread.sleep ( 11L * 1000L );
         // continue his mission 
        sched.resumeJob (job.getKey ()); // when the timer when were ordered to continue, the number of missed tasks are executed, it will by definition misfire is to perform 

        lOG.info ("The scheduler continues to execute the timer, the main thread to sleep for 15 seconds !!!! task scheduler in the thread to continue." ); 
        Thread.sleep ( 15L * 1000L );
        
        Log.info ( "Scheduler terminates execution !!!!" ); 
        sched.shutdown ( to true ); 
    } 

}

 misfire reproduce --SimpleTrigger

CronTrigger the misfire policy by personally tested all Notes reliable, SimpleTrigger all from the Xiongtai article notes, the actual results of the experiment in person please.

Thank Xiongtai: " the Quartz-Misfire missed, compensation execution "

SimpleTrigger default misfire strategy is: org.quartz.Trigger.MISFIRE_INSTRUCTION_SMART_POLICY = 0

// define the trigger, perform a 2 seconds, 5 times, 6 times in total execution 
        SimpleScheduleBuilder simpleScheduleBuilder = simpleSchedule () withIntervalInSeconds (2) .withRepeatCount (5. );
 //                 .repeatForever (); // infinite loop 
        
        / * 
           set misfire strategy: SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT =. 5 
             - is not triggered immediately executed 
            - waiting for the next trigger frequency time period, to perform FinalTime remaining number of cycles 
            - in calculation period startTime reference frequency, and to give FinalTime 
            - occurs even if the intermediate pause, resume after holding FinalTime time constant 
         * / 
        simpleScheduleBuilder.withMisfireHandlingInstructionNextWithExistingCount (); 
        
        / *
           Set misfire strategy: SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT. 4 = 
             - does not immediately trigger the execution 
            - waiting for the next trigger frequency time period, to perform FinalTime remaining number of cycles 
            - in calculation period startTime reference frequency, and to give FinalTime 
            - even if the intermediate retention time constant occurs FinalTime pause, resume later 
         * / 
        simpleScheduleBuilder.withMisfireHandlingInstructionNextWithRemainingCount (); 
        
        / * 
           set misfire strategy: SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_REMAINING_REPEAT_COUNT =. 3 
             - the current time is immediately trigger the execution of the trigger frequency 
            - the number of remaining cycles performed to FinalTIme 
            - time to schedule or scheduled recovery period as a reference frequency, FinalTime calculated based on the remaining number of times and the current time 
            - slightly greater than the adjusted FinalTime FinalTime value calculated according to the starttime 
         * /
        simpleScheduleBuilder.withMisfireHandlingInstructionNowWithRemainingCount (); 
        
        / * 
           set misfire strategy: SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT = 2 
            - the current time is immediately trigger the execution of the trigger frequency 
            - the number of remaining cycles to perform the FinalTIme 
            - or to schedule a time for recovery scheduling reference cycle frequency, FinalTime calculated based on the remaining number of times and the current time 
            - adjusted according starttime FinalTime slightly greater than the calculated value to FinalTime 
         * / 
        simpleScheduleBuilder.withMisfireHandlingInstructionNowWithExistingCount (); 
        
        / * 
           set misfire strategy: SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW. 1 = 
             - - the current time is immediately trigger the execution frequency of the trigger 
            - the remaining number of cycles performed to FinalTIme 
            - or to schedule a time for recovery scheduling periodic frequency reference, FinalTime calculated based on the remaining number of times and the current time obtained
            - Adjusted FinalTime The starttime slightly greater than the calculated value to FinalTime 
         * /
        simpleScheduleBuilder.withMisfireHandlingInstructionFireNow (); 
        
        / * 
           set policy for the misfire: Trigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY = -1 
             - immediately to miss the first time you begin a frequency 
            - the frequency redo all the missed period 
            - the next time the trigger time is greater than the frequency of occurrence after this time, perform a frequency remaining Interval sequentially 
            - co performed RepeatCount + 1 times 
         * / 
        simpleScheduleBuilder.withMisfireHandlingInstructionIgnoreMisfires ();

 

Guess you like

Origin www.cnblogs.com/zhuwenjoyce/p/11184882.html