Complete timing Task Solution Spring Integration + Timing task itself management +db persistence + cluster
Maven Dependency
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>open-source.missing.com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3.0</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.2.16.RELEASE</version>
</dependency>
Execute the SQL statement (http://www.quartz-scheduler.org/) from the GZ file downloaded from the official website , note the jar version and SQL used Scripts must remain consistent. Otherwise there will be a variety of wonderful problems. For example, the scheduled task does not execute after starting the program.
Quartz.properties Configuration
Org.quartz.jobStore.class = Org.quartz.impl.jdbcjobstore.JobStoreTX
Org.quartz.jobStore.driverDelegateClass = Org.quartz.impl.jdbcjobstore.StdJDBCDelegate
Org.quartz.jobStore.tablePrefix = Qrtz_
Org.quartz.jobStore.dataSource = MyDS
Org.quartz.jobstore.isclustered=true
Org.quartz.jobStore.clusterCheckinInterval = 60000 // cluster mode detects node failure polling interval, default seconds. If the timing interval is ten seconds , the detection interval is three seconds, if from the node failed to detect the past of two seconds, then detected that moment, will trigger 5 instances, here must pay attention.
# Org.quartz.plugins.history.LoggingJobHistoryPlugin
# Org.quartz.plugin.triggHistory.class = Org.quartz.plugins.history.LoggingTriggerHistoryPlugin
# org.quartz.plugin.triggHistory.triggerFiredMessage = Trigger \{1\}.\{0\} fired Job \{6\}.\{5\} at: \{4, date, HH:mm:ss M M/DD/YYYY}
# org.quartz.plugin.triggHistory.triggerCompleteMessage = Trigger \{1\}.\{0\} completed firing job \{6\}.\{5\} at \{4, Da Te, HH:mm:ss mm/dd/yyyy\}.
Org.quartz.scheduler.instanceName = Myclusteredscheduler
Org.quartz.threadPool.class = Org.quartz.simpl.SimpleThreadPool
Org.quartz.threadPool.threadCount = 5
Org.quartz.threadPool.threadPriority = 5
Org.quartz.scheduler.instanceid=auto
Org.quartz.plugin.shutdownhook.class = Org.quartz.plugins.management.ShutdownHookPlugin
Org.quartz.plugin.shutdownhook.cleanShutdown = True
Org.quartz.dataSource.myDS.driver = Oracle.jdbc.OracleDriver
Org.quartz.dataSource.myDS.URL = jdbc:oracle:thin:@172.23.11.49:1522:fcdb
Org.quartz.dataSource.myDS.user = Hs_fund
Org.quartz.dataSource.myDS.password = Hundsun123
Org.quartz.dataSource.myDS.maxConnections = 5
Org.quartz.datasource.myds.validationquery=select 1 from dual
Org.quartz.datasource.myds.validateoncheckout=true
Spring configuration file
<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" >
<property name= "username" value= "Hs_fund" ></property>
<property name= "Password" value= "Hundsun123" ></property>
<property name= "url" value= "jdbc:oracle:thin:@172.23.11.49:1522:fcdb" ></property>
<property name= "Driverclassname" value= "Oracle.jdbc.OracleDriver" ></property>
<property name= "maxactive" value= "ten" ></property>
<property name= "Maxidle" value= "ten" ></property>
<property name= "Minidle" value= "ten" ></property>
<property name= "maxwait" value= "10000" ></property>
<property name= "Poolpreparedstatements" value= "true"/>
<property name= "maxopenpreparedstatements" value= "/>"
</bean>
<bean class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean" >
<property name= "DataSource" >
<ref bean= "DataSource"/>
</property>
<property name= "Applicationcontextschedulercontextkey" value= "Applicationcontextkey"/>
<!--Applicationcontextschedulercontextkey: It is org.springframework.scheduling.quartz.SchedulerFactoryBean that the spring context is stored in the context of the quartz in a key/value way, You can use the key defined by Applicationcontextschedulercontextkey to get the corresponding spring context--
<property name= "Triggers" >
<list>
<ref bean= "Crontrigger"/>
<!--<ref bean= "Simpletrigger"/>--
</list>
</property>
<property name= "configlocation" value= "Classpath:quartz.properties"/>
<!--configlocation: The location to indicate the configuration file for quartz--
</bean>
<bean id= "Crontrigger" class= "Org.springframework.scheduling.quartz.CronTriggerFactoryBean" >
<property name= "Jobdetail" ref= "Examplejob"/>
<!--run every morning at 6 AM--
<property name= "cronexpression" value= "*/10 * * * *?" />
</bean>
<bean name= "Examplejob" class= "Org.springframework.scheduling.quartz.JobDetailFactoryBean" >
<property name= "Jobclass" value= "examples. Examplejob "/>
<property name= "Durability" value= "true"/>
<property name= "Requestsrecovery" value= "true"/>
<property name= "Jobdataasmap" >
<map>
<entry key= "Timeout" value= "5"/>
</map>
</property>
</bean>
Examples. Examplejob
/**
* @Title: Examplejob.java
* @Package Example
* @Description: TODO (describe what the file does in a sentence)
* @author [email protected]
* @date March 11, 2016 11:48:28
* @version V1.0
*/
Package examples;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
Import Org.quartz.JobExecutionContext;
Import org.quartz.JobExecutionException;
Import Org.springframework.scheduling.quartz.QuartzJobBean;
/**
* @author Zjhua
*
*/
public class Examplejob extends Quartzjobbean {
private static SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss. SSS ");
private int timeout;
/**
* Setter called after the examplejob is instantiated
* With the value from the Jobdetailfactorybean (5)
*/
public void setTimeout (int timeout) { // is automatically injected from The bean configuration
This.timeout = timeout;
}
protected void Executeinternal (Jobexecutioncontext ctx) throws Jobexecutionexception {
String dt = Sdf.format (new Date ());
System.out.println (Ctx.getjobdetail (). Getjobdatamap (). Get ("timeout")); // will be automatically set in the bean configuration
SYSTEM.OUT.PRINTLN (dt + "examplejob===========");
try {
Thread.Sleep (5000);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
SYSTEM.OUT.PRINTLN (dt + "Examplejob timed task End");
}
}
Test Class
/**
* @Title: Springtest.java
* @Package com.cyl
* @Description: TODO (describe what the file does in a sentence)
* @author [email protected]
* @date March 10, 2016 9:12:27
* @version V1.0
*/
Package com.cyl;
Import Javax.sql.DataSource;
Import Org.quartz.JobKey;
Import Org.quartz.Scheduler;
Import org.quartz.SchedulerException;
Import Org.quartz.impl.StdSchedulerFactory;
Import Org.quartz.impl.matchers.GroupMatcher;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;
Import Org.springframework.jdbc.core.JdbcTemplate;
Import Org.springframework.scheduling.quartz.SchedulerFactoryBean;
/**
* @author Zjhua
*
*/
public class Springtest {
public static void Main (string[] args) {
ApplicationContext context = new Classpathxmlapplicationcontext (
New string[] {"Services.xml"});
/*
Taskexecutorexample Taskexecutor = Context
. Getbean (Com.cyl.TaskExecutorExample.class);
Taskexecutor.printmessages ();
DataSource DataSource = Context.getbean (Datasource.class);
JdbcTemplate jdbctemplate = new JdbcTemplate (DataSource);
Long begin = System.currenttimemillis ();
for (int i=0;i<2000;i++) {
int countofactorsnamedjoe = Jdbctemplate.queryforobject ("SELECT count (*) from t1 where a =?", Integer.class,new string[] { "1"});
System.out.print (Countofactorsnamedjoe);
}
System.out.println ("");
Long end = System.currenttimemillis ();
System.out.println (End-begin);
*/
Schedulerfactorybean bean = Context.getbean (schedulerfactorybean.class);
try {
Scheduler Scheduler = Stdschedulerfactory.getdefaultscheduler ();
System.out.println (Scheduler.getschedulername ());
System.out.println (Bean.getscheduler (). Getschedulername ());
For (String Group:bean.getScheduler (). Getjobgroupnames ()) {
groupmatcher<jobkey> Groupmatcher = groupmatcher.groupequals (group);
For (Jobkey JobKey:bean.getScheduler (). Getjobkeys (Groupmatcher)) {
System.out.println ("Found Job identified by:" + Jobkey);
}
}
try {
Thread.Sleep (60);
SYSTEM.OUT.PRINTLN ("Timed task pause");
Bean.getscheduler (). Pauseall (); // can scheduler level, trigger level, task level, can query status and other information
Thread.Sleep (60);
Bean.getscheduler (). Resumeall ();
SYSTEM.OUT.PRINTLN ("Timed task re-open");
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
Thread.Sleep (20000);
Scheduler.shutdown ();
System.out.println (Scheduler.getschedulername () + "Closed! ");
} catch (Schedulerexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
Other points to note: When you change the quartz.properties or spring configuration file, the Quartz task definitions in the existing database are not updated, and if you want to update them, you need to The quartz API is updated, or the quartz table is rebuilt and the app is restarted.
Other scheduled tasks and trigger actions
Scheduler paused
Bean.getscheduler (). Pauseall ();
Delete Trigger
Bean.getscheduler (). Unschedulejob (New Triggerkey ("Crontrigger", "DEFAULT"));
Delete a task
Bean.getscheduler (). Deletejob (New Jobkey ("Examplejob", "DEFAULT"));
Create a task
Jobdatamap Jobdatamap = new Jobdatamap ();
Jobdatamap.put ("Timeout", 5);
Jobdetail JD = Jobbuilder.newjob (examples. Examplejob.class)
. Setjobdata (Jobdatamap). Withidentity (New Jobkey ("Examplejob", "DEFAULT"). Requestrecovery (True). storedurably ( true). Build ();
Create a Trigger
Crontriggerimpl trigger = new Crontriggerimpl ();
try {
Trigger.setcronexpression ("*/20 * * * *?");
Trigger.setkey (New Triggerkey ("Crontrigger", "DEFAULT"));
Start a dispatch trigger
Bean.getscheduler (). Schedulejob (Jd,trigger);
once you know the API , you can not include any trigger and jobdetail definitions in the spring configuration file , but instead dynamically manage them based on the configuration in the database (of course, We also use this method).
Complete timing Task Solution Spring Integration + Timing task itself management +DB Persistence + cluster