Premise preparation:
First establish a 11 meter quartz need (I use an Oracle database) in the database, provided a different initialization files based on different database sql quartz respectively, sql file path in quartz-2.3.0-SNAPSHOT-0724 \ src \ org \ quartz \ impl \ jdbcjobstore follows:
ScheduleBuilder is trigger rules trigger trigger custom class, there are four kinds of triggers its implementation class: CalendarIntervalScheduleBuilder, CronScheduleBuilder, DailyTimeIntervalScheduleBuilder , SimpleScheduleBuilder.
#############################################################################################################################################
1, 11 timed manner are stored in different tables in different tables of data to a different
Here demonstrates CronScheduleBuilder and SimpleScheduleBuilder two kinds of timing modes, respectively, behind the implementation StoreSimpleTrigger2OracleExample.java and StoreCronTrigger2OracleExample.java be able to see the difference between a database as follows:
#############################################################################################################################################
This is achieved in 4 when storing a task class, respectively, will have different data table in the database 11, color coded insert statement as follows:
* qrtz_blob_triggers from the SELECT; - do not insert statement says that this table has no data
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
select * from qrtz_calendars;
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
select * from qrtz_cron_triggers;
Insert into QRTZ_CRON_TRIGGERS (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP,CRON_EXPRESSION,TIME_ZONE_ID)
values ('SchedulerJoyce0725','cronTrigger','cronGroup1','0/5 * * * * ?','Asia/Shanghai');
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
select * from qrtz_fired_triggers;
Insert into QRTZ_FIRED_TRIGGERS (SCHED_NAME,ENTRY_ID,TRIGGER_NAME,TRIGGER_GROUP,INSTANCE_NAME,FIRED_TIME,SCHED_TIME,PRIORITY,STATE,JOB_NAME,JOB_GROUP,IS_NONCONCURRENT,REQUESTS_RECOVERY)
values ('SchedulerJoyce0725','InstanceJoyce07251564061848994','cronTrigger','cronGroup1','InstanceJoyce0725',1564061855002,1564061855000,5,'EXECUTING','simpleRecoveryJob','cronGroup1','0','0'); --每一次远程启动时ENTRY_ID总是会变一变
Insert into QRTZ_FIRED_TRIGGERS (SCHED_NAME,ENTRY_ID,TRIGGER_NAME,TRIGGER_GROUP,INSTANCE_NAME,FIRED_TIME,SCHED_TIME,PRIORITY,STATE,JOB_NAME,JOB_GROUP,IS_NONCONCURRENT,REQUESTS_RECOVERY) values ('SchedulerJoyce0725','InstanceJoyce07251564066439267','simpleTriger1','simpleGroup','InstanceJoyce0725',1564066446293,1564066451270,5,'ACQUIRED',null,null,'0','0');
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
select * from qrtz_job_details;
Insert into QRTZ_JOB_DETAILS (SCHED_NAME,JOB_NAME,JOB_GROUP,DESCRIPTION,JOB_CLASS_NAME,IS_DURABLE,IS_NONCONCURRENT,IS_UPDATE_DATA,REQUESTS_RECOVERY,JOB_DATA)
values ('SchedulerJoyce0725','simpleRecoveryJob','cronGroup1',null,'org.quartz.examples.example15.SimpleRecoveryJob','0','0','0','0',
TO_BLOB(HEXTORAW('...'))|| TO_BLOB(HEXTORAW('...')));
Insert into QRTZ_JOB_DETAILS (SCHED_NAME,JOB_NAME,JOB_GROUP,DESCRIPTION,JOB_CLASS_NAME,IS_DURABLE,IS_NONCONCURRENT,IS_UPDATE_DATA,REQUESTS_RECOVERY,JOB_DATA)
values ('SchedulerJoyce0725','simpleJob1','simpleGroup',null,'org.quartz.examples.example15.SimpleRecoveryJob','0','0','0','1',
TO_BLOB(HEXTORAW('...'))|| TO_BLOB(HEXTORAW('...')));
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
select * from qrtz_locks;
Insert into qrtz_locks (SCHED_NAME,LOCK_NAME) values ('SchedulerJoyce0725','STATE_ACCESS');
Insert into qrtz_locks (SCHED_NAME,LOCK_NAME) values ('SchedulerJoyce0725','TRIGGER_ACCESS');
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
select * from qrtz_paused_trigger_grps;
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
select * from qrtz_scheduler_state;
Insert into qrtz_scheduler_state (SCHED_NAME,INSTANCE_NAME,LAST_CHECKIN_TIME,CHECKIN_INTERVAL)
values ('SchedulerJoyce0725','InstanceJoyce0725',1564061857522,7500);
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
select * from qrtz_simple_triggers;
Insert into QRTZ_SIMPLE_TRIGGERS (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP,REPEAT_COUNT,REPEAT_INTERVAL,TIMES_TRIGGERED)
values ('SchedulerJoyce0725','simpleTriger1','simpleGroup',20,5000,2);
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
select * from qrtz_simprop_triggers;
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
select * from qrtz_triggers;
Insert into qrtz_triggers (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP,JOB_NAME,JOB_GROUP,DESCRIPTION,NEXT_FIRE_TIME,PREV_FIRE_TIME,PRIORITY,TRIGGER_STATE,TRIGGER_TYPE,START_TIME,END_TIME,CALENDAR_NAME,MISFIRE_INSTR,JOB_DATA)
values ('SchedulerJoyce0725','cronTrigger','cronGroup1','simpleRecoveryJob','cronGroup1',null,1564061865000,1564061860000,5,'ACQUIRED','CRON',1564061849000,0,null,0, EMPTY_BLOB());
Insert into QRTZ_TRIGGERS (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP,JOB_NAME,JOB_GROUP,DESCRIPTION,NEXT_FIRE_TIME,PREV_FIRE_TIME,PRIORITY,TRIGGER_STATE,TRIGGER_TYPE,START_TIME,END_TIME,CALENDAR_NAME,MISFIRE_INSTR,JOB_DATA) values ('SchedulerJoyce0725','simpleTriger1','simpleGroup','simpleJob1','simpleGroup',null,1564066451270,1564066446270,5,'ACQUIRED','SIMPLE',1564066441270,0,null,0, EMPTY_BLOB());
#############################################################################################################################################
2, job task class, SimpleRecoveryJob.java
#############################################################################################################################################
package org.quartz.examples.example15; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.JobKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; /** * 一个job作业。 */ public class SimpleRecoveryJob implements Job { private static Logger LOG = LoggerFactory.getLogger(SimpleRecoveryJob.class); private static Final String COUNT = "COUNT" ; // must be modified public constructor with no arguments public SimpleRecoveryJob () { } // task execution method public void Execute (the JobExecutionContext context) throws JobExecutionException { JobKey JobKey = context.getJobDetail (). getKey (); // , this method returns true if the result of "recovery" and re-execute the job situation. IF (context.isRecovering ()) { log.info ( "recovery job: SimpleRecoveryJob:" + + JobKey "RECOVERING AT" + new new a Date ()); } the else { log.info ("不恢复作业:SimpleRecoveryJob: " + jobKey + " starting at " + new Date()); } JobDataMap data = context.getJobDetail().getJobDataMap(); int count; if (data.containsKey(COUNT)) { count = data.getInt(COUNT); } else { count = 0; } count++; data.put(COUNT, count); LOG.info("SimpleRecoveryJob: " + jobKey + " done at " + new Date() + "\n Execution #" + count); } }
#############################################################################################################################################
3, a simple timer task stored in the database table, StoreSimpleTrigger2OracleExample.java
#############################################################################################################################################
package org.quartz.examples.example15; import static org.quartz.DateBuilder.futureDate; import static org.quartz.JobBuilder.newJob; import static org.quartz.SimpleScheduleBuilder.simpleSchedule; import static org.quartz.TriggerBuilder.newTrigger; import org.quartz.DateBuilder.IntervalUnit; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerFactory; import org.quartz.SimpleTrigger; import org.quartz.impl.StdSchedulerFactory; import org.slf4j.Logger; Import org.slf4j.LoggerFactory; / ** * Simple timing of tasks stored in the database table. * Job tasks stored in the database, where the print job tasks are: no recovery job ...... * / public class StoreSimpleTrigger2OracleExample { Private static Logger LoggerFactory.getLogger the LOG = (StoreSimpleTrigger2OracleExample. Class ); public void RUN ( Boolean inClearJobs, Boolean inScheduleJobs) throws Exception { // initialization scheduler the SchedulerFactory SF = new new the StdSchedulerFactory (); scheduler sched = sf.getScheduler (); IF (inClearJobs) { sched.clear(); LOG.warn("***** Deleted existing jobs/triggers *****"); } LOG.info("------- Initialization Complete -----------"); if (inScheduleJobs) { LOG.info("------- Scheduling Jobs ------------------"); String schedId = sched.getSchedulerInstanceId(); // ======================================================== // ============ job1 // ======================================================== int count = 1; JobDetail job = newJob(SimpleRecoveryJob.class).withIdentity("simpleJob" + count, "simpleGroup").requestRecovery() // 如果job执行过程中宕机,则job重新执行 .build(); SimpleTrigger trigger = newTrigger().withIdentity("simpleTriger" + count, "simpleGroup") .startAt(futureDate(1, IntervalUnit.SECOND)) .withSchedule(simpleSchedule().withRepeatCount(20).withIntervalInSeconds(5)).build(); LOG.info(job.getKey() + " will run at: " + trigger.getNextFireTime() + " and repeat: " Trigger.getRepeatCount + () + "Times, Every" + trigger.getRepeatInterval () / 1000 + "seconds The" ); sched.scheduleJob (Job, Trigger); // // // =========== ============================================= // // = JOB2 =========== // // ================================== ====================== // COUNT ++; // the Job = newJob (SimpleRecoveryJob.class) .withIdentity ( "job0724_" + COUNT, schedId) .requestRecovery ( ) // If the job execution process downtime, re-execute the job // .build (); // the Trigger = newTrigger (). withIdentity ( "triger0724_" + COUNT, schedId) .startAt (futureDate (2, IntervalUnit.SECOND)) // .withSchedule(simpleSchedule().withRepeatCount(20).withIntervalInSeconds(5)).build(); // LOG.info(job.getKey() + " will run at: " + trigger.getNextFireTime() + " and repeat: " // + trigger.getRepeatCount() + " times, every " + trigger.getRepeatInterval() / 1000 + " seconds"); // sched.scheduleJob(job, trigger); } LOG.info("------- Starting Scheduler ---------------"); sched.start(); try { Thread.sleep(3600L * 1000L); } catch (Exception e) { // } sched.shutdown(); LOG.info("------- Shutdown Complete ----------------"); } public static void main(String[] args) throws Exception { boolean clearJobs = true; // 是否清空job任务 boolean scheduleJobs = true; // 是否调度任务 for (String arg : args) { if (arg.equalsIgnoreCase("clearJobs")) { clearJobs = true; } else if (arg.equalsIgnoreCase("dontScheduleJobs")) { scheduleJobs = false; } } StoreSimpleTrigger2OracleExample example = new StoreSimpleTrigger2OracleExample(); example.run(clearJobs, scheduleJobs); } }
#############################################################################################################################################
4, cron timer task definitions stored in the database table, StoreCronTrigger2OracleExample.java
#############################################################################################################################################
Package org.quartz.examples.example15; Import static org.quartz.CronScheduleBuilder.cronSchedule; Import static org.quartz.JobBuilder.newJob; Import static org.quartz.TriggerBuilder.newTrigger; Import java.util.Date; Import org.quartz .CronTrigger; Import org.quartz.JobDetail; Import org.quartz.Scheduler; Import org.quartz.SchedulerFactory; Import org.quartz.impl.StdSchedulerFactory; Import org.slf4j.Logger; Import org.slf4j.LoggerFactory; / ** * cron定义定时任务存储到数据库表。 * storage tasks to the job database, job printing task here is: do not restore job ...... * / public class StoreCronTrigger2OracleExample { Private static Logger LoggerFactory.getLogger the LOG = (StoreCronTrigger2OracleExample. Class ); public void RUN ( Boolean inClearJobs) throws Exception { // initialization scheduler the SchedulerFactory SF = new new the StdSchedulerFactory (); scheduler sched = sf.getScheduler (); IF (inClearJobs) { sched.clear (); LOG.warn ( "***** Deleted existing Jobs / Triggers ** *** " ); } // =============================================== ========= // ============ the jobs that job1 performed once every 20 seconds, repeated indefinitely // =============== ========================================= the JobDetail Job = newJob (SimpleRecoveryJob. class ) .withIdentity ( "simpleRecoveryJob_Recovery", "cronGroup2" ) .requestRecovery () // If the job task where the service is down for other reasons job or task is interrupted, please mark JobExecutionContext.isRecovering () = true. // Let me know how you can get this tag to fit the business scene. // but only after recovery tasks for the first time to perform tasks, get Recovering mark is true, after which the task Recovering marks for value and false. .build (); // executed once every 5 seconds CronTrigger trigger = newTrigger().withIdentity("cronTrigger_Recovery", "cronGroup2").withSchedule(cronSchedule("0/5 * * * * ?")).build(); Date ft = sched.scheduleJob(job, trigger); LOG.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: " + trigger.getCronExpression()); LOG.info("------- Starting Scheduler ---------------"); sched.start(); try { Thread.sleep(3600L * 1000L); } catch (Exception e) { // } // suspended from their duties sched.pauseJob (job.getKey ()); log.info ( . "Scheduler to suspend the timer, the main thread to sleep for 11 seconds !!!! miss regular tasks performed N times when the timing simulation job1 thread of execution is due not grab CPU time or other events implementation of miss. " ); Thread.sleep ( 11L * 1000L ); // continue his mission sched.resumeJob (job.getKey ()); // when the timing when is get the command to continue, the number of missed tasks are executed, it will by definition misfire is to perform sched.shutdown (); log.info ( "------- ------- Complete Shutdown --------- " ); } public static void main (String [] args) throws Exception { Boolean clearJobs = to false ; //Empty whether job tasks StoreCronTrigger2OracleExample Example = new new StoreCronTrigger2OracleExample (); example.run (clearJobs); } }
#############################################################################################################################################
5, the task execution timing database, RunOracleExistingJobExample.java
#############################################################################################################################################
Package org.quartz.examples.example15; Import org.quartz.Scheduler; Import org.quartz.SchedulerFactory; Import org.quartz.impl.StdSchedulerFactory; Import org.slf4j.Logger; Import org.slf4j.LoggerFactory; / ** * first run ClusterExample.java, to determine the Oracle database job tasks already exist. * print job task here is to recover from a database table back, so the first time to perform these tasks will be printed: restoration work ...... * After that job tasks to print only: no recovery job ...... * / public class RunOracleExistingJobExample { Private static Logger LoggerFactory.getLogger the LOG = (RunOracleExistingJobExample. class ); public void RUN ( Boolean inClearJobs) throws Exception { // 初始化调度器 SchedulerFactory sf = new StdSchedulerFactory(); Scheduler sched = sf.getScheduler(); if (inClearJobs) { sched.clear(); LOG.warn("***** Deleted existing jobs/triggers *****"); } LOG.info("------- Starting Scheduler ---------------"); sched.start(); try { Thread.sleep(3600L * 1000L); } catch (Exception e) { // } Sched.shutdown (); log.info ( "------- ---------------- the Shutdown Complete" ); } public static void main (String [] args ) throws Exception { Boolean clearJobs = to false ; // if empty job task here is not clear RunOracleExistingJobExample Example = new new RunOracleExistingJobExample (); example.run (clearJobs); } }