Note: The use of single-node quartz is not described here in detail, directly advanced to the distributed cluster version of the
1. Preparatory work:
Using the environment spring4.3.5,quartz2.2.3, the persistence framework JdbcTemplate
The pom file is as follows
<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >< Modelversion>4.0.0</modelversion><groupid>com.dzpykj</groupid><artifactid> Quartz-test</artifactid><version>0.0.1-snapshot</version><packaging>war</packaging ><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>< spring.version>4.3.5.release</spring.version></properties><dependencies><!--https:// Mvnrepository.com/artifact/org.quartz-scheduler/quartz--><dependency><groupid> org.quartz-scheduler</groupid><artifactid>quartz</artifactid><version>2.2.3</ version></dependency><!--servlet 3--><dependency><groupid>javax.servlet</groupid ><artifactid>javax.servlet-api</artifactid><version>3.0.1</version></dependency><!--Spring Dependencies--><dependency> <groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId> <version>${spring.version}</version></dependency><dependency><groupId> org.springframework</groupid><artifactid>spring-expression</artifactid><version>${ spring.version}</version></dependency><dependency><groupid>org.springframework</ Groupid><artifactid>spring-core</artifactid><version>${spring.version}</version> </dependency><dependency><groupId>org.springframework</groupId><artifactId> Spring-web</artifactid><version>${spring.version}</version></dependency><dependency ><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId>< Version>${spring.version}</versIon></dependency><dependency><groupid>org.springframework</groupid><artifactid >spring-context</artifactId><version>${spring.version}</version></dependency>< Dependency><groupid>org.springframework</groupid><artifactid>spring-beans</artifactid ><version>${spring.version}</version></dependency><dependency><groupId> org.springframework</groupid><artifactid>spring-aop</artifactid><version>${ spring.version}</version></dependency><dependency><groupid>org.springframework</ Groupid><artifactid>spring-aspects</artifactid><version>${spring.version}</version> </dependency><dependency><groupId>org.springframework</groupId><artifactId> Spring-orm</artifactid><version>${spring.version}</version></dependency><dependency ><groupid>org.springframework&lT;/groupid><artifactid>spring-test</artifactid><version>${spring.version}</version> <scope>test</scope></dependency><dependency><groupId>mysql</groupId>< Artifactid>mysql-connector-java</artifactid><version>5.1.38</version></dependency> <dependency><groupId>commons-pool</groupId><artifactId>commons-pool</artifactId> <version>1.6</version></dependency><dependency><groupid>commons-dbcp</groupid ><artifactId>commons-dbcp</artifactId><version>1.4</version></dependency>< Dependency><groupid>org.springframework</groupid><artifactid>spring-tx</artifactid> <version>4.3.5.RELEASE</version></dependency><dependency><groupId> org.springframework</groupid><artifactid>spring-jdbc</artifactid><version>4.3.5. Release</version></depenDency><dependency><groupid>org.apache.commons</groupid><artifactid>commons-lang3 </artifactId><version>3.7</version></dependency></dependencies><build>< plugins><!--A plugin for war--><plugin><groupid>org.apache.maven.plugins</groupid>< artifactid>maven-war-plugin</artifactid><version>2.6</version></plugin><!--Compile Plugin- -><plugin><artifactid>maven-compiler-plugin</artifactid><version>3.5.1</version ><configuration><source>1.8</source><target>1.8</target><encoding>utf-8 </encoding></configuration></plugin></plugins><finalName>qt</finalName> </build></project>
2. Database Build table: 11 photos
Official website Download 2.2.3 Address: http://www.quartz-scheduler.org/downloads/
After downloading the statements in the SQL file to the database execution
3. Configure the database to Quartz configuration file quartz.properties
Org.quartz.scheduler.instanceName = TestScheduler1 Org.quartz.scheduler.instanceId = AUTO Org.quartz.threadPool.class = Org.quartz.simpl.SimpleThreadPoolorg.quartz.threadPool.threadCount = 10org.quartz.threadpool.threadpriority = 5org.quartz.threadpool.threadsinheritcontextclassloaderofinitializingthread = Trueorg.quartz.jobStore.misfireThreshold = 60000org.quartz.jobstore.class = Org.quartz.impl.jdbcjobstore.JobStoreTXorg.quartz.jobStore.dataSource = MyDS org.quartz.jobstore.driverdelegateclass= Org.quartz.impl.jdbcjobstore.StdJDBCDelegateorg.quartz.jobStore.tablePrefix = Qrtz_ Org.quartz.jobstore.maxmisfirestohandleatatime=10org.quartz.jobstore.isclustered = True Org.quartz.jobStore.clusterCheckinInterval = 10000org.quartz.datasource.myds.driver = Com.mysql.jdbc.Driverorg.quartz.dataSource.myDS.URL =jdbc\:mysql\://127.0.0.1\:3306/quartz_test?useunicode\= True&characterencoding\=utf8&autoreconnect\=trueorg.quartz.datasource.myds.user = Rootorg.quartz.dataSource.myDS.password =rOot org.quartz.dataSource.myDS.maxConnections = 5
4. Configuring the Applicationcontext-quartz.xml File
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:task= "Http://www.springframework.org/schema/task" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd http://Www.springframework.org/schema/taskhttp://www.springframework.org/schema/task/spring-task.xsd"><!--quartz cluster Schduler--<bean id= "Clusterquartzscheduler"class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean" > <!--triggers integrated dynamic configuration-<!--& Lt;property name= "triggers" > <list> <ref bean= "Allocationplantrigger"/> </list> </property> <!--quartz configuration file path, point to cluster configuration-<property name= "Configlocation" value= "Classpath:quartz.properties"/> <!--started with 0 seconds to start the task--<property name= "STA Rtupdelay "value=" 0 "/> <!--the data source required to save the job data to the database-<!--<property name=" DataSource "ref=" data Source "/>-<!--job accepts APPLICATIONCONTEXT member variable name--<property name=" applicationcontextsched Ulercontextkey "value=" ApplicationContext "/> <!--modify job, update to database--<property name=" Overwriteex Istingjobs "value=" true "/> </bean></beans>
5. Build Tool Class
Packagecom.dzpykj.plugins.quartz.dynamic;Import StaticOrg.quartz.CronScheduleBuilder.cronSchedule;Import StaticOrg.quartz.JobBuilder.newJob;Import StaticOrg.quartz.TriggerBuilder.newTrigger;ImportJava.text.SimpleDateFormat;Importjava.util.Date;Importjava.util.List;ImportOrg.quartz.CronTrigger;ImportOrg.quartz.JobDetail;ImportOrg.quartz.JobKey;Importorg.quartz.ObjectAlreadyExistsException;ImportOrg.quartz.Scheduler;Importorg.quartz.SchedulerException;Importorg.quartz.SchedulerFactory;ImportOrg.quartz.TriggerKey;Importorg.quartz.impl.StdSchedulerFactory;Importorg.springframework.jdbc.core.JdbcTemplate; Public classQuartztaskutils { Public Staticstring AddTask (String jobName, String jobgroupname, String triggername, String triggergroupname, String cr Onexp, Class Jobclass, JdbcTemplate jdbctemplate) {Try{SimpleDateFormat SDF=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Schedulerfactory schedulerfactory=Newstdschedulerfactory (); Scheduler Scheduler=Schedulerfactory.getscheduler (); Jobdetail Jobdetail=newjob (Jobclass). Withidentity (JobName, Jobgroupname). Build (); Crontrigger Simpletrigger=Newtrigger (). Withidentity (Triggername, Triggergroupname). Withschedule (Cronschedule (CRONEXP)). Star Tnow (). build (); Date ft=scheduler.schedulejob (Jobdetail, Simpletrigger); Scheduler.start (); System.err.println ("Timed Tasks Start Execution"); } Catch(objectalreadyexistsexception e) {e.printstacktrace (); return"Job name or trigger name with duplicate names in the same group"; } Catch(schedulerexception e) {e.printstacktrace (); return"Save timed task exception"; } return"Success"; } Public Staticstring Removejob (String jobName, String jobgroupname, String triggername, String triggergroupname, Jdbctem Plate JdbcTemplate) {Try{String Jobsql= "SELECT * from qrtz_triggers where job_name =?" and Job_group =? "; List joblist=jdbctemplate.queryforlist (Jobsql, JobName, jobgroupname); if(Joblist.size () < 1) { return"Database does not have this task"; } schedulerfactory schedulerfactory=Newstdschedulerfactory (); Scheduler Scheduler=Schedulerfactory.getscheduler (); Triggerkey Triggerkey=NewTriggerkey (Triggername, triggergroupname); Scheduler.pausetrigger (Triggerkey);//Stop TriggerScheduler.unschedulejob (Triggerkey);//Remove a triggerJobkey Jobkey =NewJobkey (JobName, jobgroupname); Scheduler.deletejob (Jobkey);//Delete a task}Catch(schedulerexception e) {e.printstacktrace (); return"Fail"; } return"Success"; }}
Test URLs that might be used
Test quartz distributed cluster, two ports to start Tomcat, visit once each visit, watch the console, look at the database table, slowly study, there will be a harvest
New Task Urlhttp://127.0.0.1:8080/addtask?jobname=uservisitcountjob1&jobgroupname= Uservisitcountjobgroup1&triggername=simpletrigger1&triggergroupname=triggergroup1 Delete Task urlhttp: //127.0.0.1:8080/removetask?jobname=uservisitcountjob1&jobgroupname= Uservisitcountjobgroup1&triggername=simpletrigger1&triggergroupname=triggergroup1
These are just some key steps to explain
The github address of the code for everyone to download the full code HTTPS://GITHUB.COM/PINBO1991/QT
References to the great gods in the process of writing code: https://www.cnblogs.com/jiafuwei/p/6145280.html and Https://www.cnblogs.com/kingpeng/p/7137384.html For everyone to understand.
The quartz.properties configuration is detailed below
#Configure Main Scheduler Properties #==============================================================#配置集群时, the ID of the quartz scheduler, due to the configuration of the cluster, there is only one scheduler, you must ensure that the value of each server is the same, you can not modify, as long as each AMS is the same line Org.quartz.scheduler.instanceName =Scheduler1 #集群中每台服务器自己的id, auto means auto-generated without modification org.quartz.scheduler.instanceId=AUTO #==============================================================#Configure ThreadPool #==============================================================#quartz线程池的实现类 without modifying the org.quartz.threadPool.class=Org.quartz.simpl.SimpleThreadPool #quartz线程池中线程数, can be adjusted according to the number of tasks and the degree of responsibility Org.quartz.threadPool.threadCount= 5#quartz线程优先级 org.quartz.threadPool.threadPriority= 5 #==============================================================#Configure Jobstore #==============================================================#表示如果某个任务到达执行时间, when there are no available threads in the thread pool, the maximum time the task waits, if the wait time exceeds the value configured below (in milliseconds), this time is not executing, and waiting for the next execution time, can be adjusted according to the amount of task and the degree of responsibility Org.quartz.jobStore.misfireThreshold= 60000#实现集群时, the way the task is stored, Org.quartz.impl.jdbcjobstore.JobStoreTX represents the database storage without modifying the Org.quartz.jobStore.class=Org.quartz.impl.jdbcjobstore.JobStoreTX #quartz存储任务相关数据的表的前缀, no need to modify Org.quartz.jobStore.tablePrefix=Qrtz_ #连接数据库数据源名称, consistent with the Org.quartz.dataSource.myDS myds in the configuration below, can be done without modification Org.quartz.jobStore.dataSource=MyDS #是否启用集群, enable, change to true, note: After you enable the cluster, you must configure the following data source, or the quartz scheduler will fail to initialize org.quartz.jobStore.isClustered=false#集群中服务器相互检测间隔, each server will update its state to the server at the interval configured below, and if a server is not checkin for more than the following time, the scheduler will assume that the server is down, and no more tasks will be assigned to that server Org.quartz.jobStore.clusterCheckinInterval= 20000 #==============================================================#Non-Managed Configure Datasource #==============================================================#配置连接数据库的实现类, you can refer to the configuration in the IAM database configuration file org.quartz.dataSource.myDS.driver=com.mysql.jdbc.Driver #配置连接数据库连接, you can refer to the configuration in the IAM database configuration file Org.quartz.dataSource.myDS.URL= Jdbc:mysql://localhost:3306/test#配置连接数据库用户名 Org.quartz.dataSource.myDS.user=Yunxi #配置连接数据库密码 Org.quartz.dataSource.myDS.password= 123456#配置连接数据库连接池大小, typically twice times the org.quartz.dataSource.myDS.maxConnections of the thread pool configured above= 10
Quartz Spring Distributed Cluster Build demo