Did a simple scheduled task.
One, dependence
<dependencies><!--<dependency> <groupId>org.springframework.boot</groupId> < Artifactid>spring-boot-starter-quartz</artifactid> </dependency>--><dependency>< groupid>org.postgresql</groupid><artifactid>postgresql</artifactid><version>42.2.2 </version></dependency><dependency><groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency>< Groupid>org.springframework.boot</groupid><artifactid>spring-boot-starter-web</artifactid ></dependency><!--Https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter-- <dependency><groupid>com.alibaba</groupid><artifactid>druid-spring-boot-starter</ Artifactid><version>1.1.10</version></dependency><dependency><groupid> Org.quartz-scheduler</groupid><artifactid>quartz</artifactid><version>2.2.3</version></dependency>< Dependency><groupid>org.quartz-scheduler</groupid><artifactid>quartz-jobs</artifactid ><version>2.2.3</version></dependency><dependency><groupId> org.mybatis.spring.boot</groupid><artifactid>mybatis-spring-boot-starter</artifactid>< version>1.3.2</version></dependency><dependency><groupid>org.springframework</ Groupid><artifactid>spring-context-support</artifactid></dependency><dependency> <groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional> true</optional></dependency><!--Https://mvnrepository.com/artifact/com.alibaba/fastjson-- <dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId>< Version>1.2.47</version></dependency><!--Spring-boot-devtools Dependency Package--><dependency><groupid>org.springframework.boot</groupid ><artifactid>spring-boot-devtools</artifactid><optional>true</optional><scope >true</scope></dependency><!--servlet dependency. <dependency><groupid>javax.servlet</groupid><artifactid>javax.servlet-api</ artifactid><scope>provided</scope></dependency>--><!--https://mvnrepository.com/ Artifact/javax.servlet/jstl--><dependency><groupid>javax.servlet</groupid><artifactid >jstl</artifactid><version>1.2</version></dependency><dependency><groupid >org.apache.tomcat.embed</groupid><artifactid>tomcat-embed-jasper</artifactid><scope >provided</scope></dependency><dependency><groupid>org.springframework.boot</ groupid><artifactid>spring-boot-starter-test</artifactid><Scope>test</scope></dependency></dependencies>
Do not change the version and order of dependencies above, otherwise there will be problems
Second, application.yml
Spring:quartz: #相关属性配置 properties:org:quartz:scheduler:instanceName:clustered Scheduler Instanceid:auto JobStore:class:org.quartz.impl.jdbcjobstore.JobStoreTX DriverDelegateClass:org.quartz.impl.jdbcjobstore.PostgreSQLDelegate Tableprefix:qrtz_ Iscluste Red:true clustercheckininterval:10000 Useproperties:false Datasource:quartz ThreadPool:class:org.quartz.simpl.SimpleThreadPool threadcount:10 Threadpriority:5 Threadsinheritcontextclassloaderofinitializingthread:true Plugin:jobinitializer: Class:org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin FileNames:quartz_jobs.xml FAI Lonfilenotfound:true scaninterval:1000 wrapinusertransaction:false #数据库方式 Job-store-typ E:JDBC #初始化表结构 #jDBC: #initialize-schema:never datasource:druid:driver-class-name:org.postgresql.driver Url:jdbc:po Stgresql://127.0.0.1:5432/quartz username:admin password:123456 Jpa:properties:hibernate:te Mp:use_jdbc_metadata_defaults:false ddl-auto:create #ddl-auto: Set to update indicates that the new table is not re-created each time show-sql:true Mvc:view:prefix:/web-inf/jsp/suffix:. JSP http:encoding:charset:utf-8 Enabled:true Force:true Mybatis:mapperlocations:classpath:mapper/*.xml TypeAliasesPackage:tk.mapper.model # # application:# name:quartz-cluster-node-secondserver:port:8083 Servlet:context-path:/test################### ################################################################################### Print Log Logging:level:root:INFO Org.hibernate:INFO Org.hibernate.type.descriptor.sql.BasicBinder:TRACE org.hibernate.type.descriptor.sql.BasicEx Tractor:trace Com.spriNgms:debug com.lyw.timers.mapper:debug######################################################################### ############################## #JSP ########################################################
Modify the information of the database according to the situation
A City initialized tasks
<?xml version= "1.0" encoding= "UTF-8"? ><job-scheduling-dataxmlns= "http://www.quartz-scheduler.org/xml/ Jobschedulingdata "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation="/HTTP/ Www.quartz-scheduler.org/xml/JobSchedulingData http://www.quartz-scheduler.org/xml/job_scheduling_data_2_0.xsd " version= "2.0" > <pre-processing-commands> <!--<delete-jobs-in-group>*</delete-jobs-i N-group>-<delete-triggers-in-group>*</delete-triggers-in-group> </pre-pro Cessing-commands> <processing-directives> <overwrite-existing-data>true</overwrite -existing-data> <ignore-duplicates>false</ignore-duplicates> </processing-directiv Es><schedule> <job><name>PrvdDataJob</name><group>DayEnd</group>< Description>timer</description><job-class>com.lyw.timers.prvddatajob</job-class></job><trigger><cron><name>prvddatajobtrigger</name><group> Trigger_dayend</group><job-name>prvddatajob</job-name><job-group>dayend</job-group ><CRON-EXPRESSION>*/3 * * * * * </cron-expression></cron></trigger></schedule></ Job-scheduling-data>
And put them in application.yml.
Iv. Defining a Task class
@Component ("Prvddatajob") public class Prvddatajob implements job{static Logger Logger = Loggerfactory.getlogger ( Prvddatajob.class);p ublic prvddatajob () {} @Overridepublic void execute (jobexecutioncontext context) throws jobexecutionexception {try {System.out.println ((Crontrigger) Context.gettrigger ()). Getcronexpression ());// System.out.println ("My 3 seconds at a Time");} catch (Exception e) {throw new Jobexecutionexception ("Execute Prvddatajob Task exception", e);}}}
How far service class
@Servicepublic class Timersservice {@Autowiredprivate Scheduler Scheduler; @Autowiredprivate timermapper timermapper; Public String SetTimer (Timervo tvo) throws Exception{return Buildtimer (TVO);} /** * This method is used to get to the corresponding task and set */public String Buildtimer (Timervo tvo) throws Exception{timer timer = new timer (); Beanutils.copyproperties (TVO, timer); Query for a task named Triggername timer = Timermapper.getcrontrigger (timer); Record the last expression timer.setbeforeexpression (Timer.getexpression ()); String expression = ""; if (Tvo.getmonth (). Length () >0) {expression = Tvo.getsecord () + "" +tvo.getminute () + "" +tvo.gethour () + "" +tvo.getday ( ) + "" +tvo.getmonth () + "?";} if (Tvo.getmonth (). Length () <=0 && tvo.getday (). Length () >0) {expression = Tvo.getsecord () + "" + Tvo.getminute () + "+tvo.gethour () +" "+tvo.getday () +" *? ";} if (Tvo.getweek (). Length () >0) {expression = Tvo.getsecord () + "" +tvo.getminute () + "" +tvo.gethour () + "? *" +tvo.getwee K (); } tiMer.setexpression (expression); Set the start time to one time in seconds//data has a task trigger if (timer.getname () = null) {//set Triggerkey Triggerkey Triggerkey = Trigg Erkey.triggerkey (Timer.getname (), Timer.getgroup ()); Set Jobkeyjobkey Jobkey = Jobkey.jobkey (Timer.getjobname (), Timer.getjobgroup ()); Determine if the current task exists in Boolean isexists = Scheduler.checkexists (Triggerkey); if (isexists) {//Stop task//Scheduler.pausetrigger (Triggerkey);//Scheduler.pausejob (Jobkey); Update task time setting Timermapper.updatebynameandgroup (timer); Start Task Scheduler.resumejob (Jobkey); Scheduler.resumetrigger (Triggerkey); Scheduler.start (); }} return toString (timer);} Public String toString (timer timer) {String beforeexpression = timer.getbeforeexpression (). Replace ("*", ""). Replace ("/ "," "). Replace ("? "," ""). Trim (); String expression = timer.getexpression (). Replace ("*", ""). Replace ("/", ""). Replace ("?", ""). Trim (); StringBuffer sb = new StringBuffer ("Task Name:" +timer.getjobname ()); Sb.appEnd ("\r\n<br/>"); Sb.append ("Task belongs to Group:" +timer.getjobgroup ()); Sb.append ("\r\n<br/>"); Sb.append ("last time setting : every "+beforeexpression+"); Sb.append ("\r\n<br/>"); Sb.append ("Current time setting: once per" +expression+ "seconds"); return Sb.tostring ();}}
Six, the last timer and Timervo class
public class Timervo extends Timer{private string month;private string day;private string Week;private string hour;private String Minute;private string Secord;public string GetMonth () {return month;} public void Setmonth (String month) {this.month = month;} Public String GetDay () {return day;} public void Setday (String day) {this.day = day;} Public String Getweek () {return week;} public void Setweek (String week) {This.week = week;} Public String Gethour () {return hour;} public void Sethour (String hour) {this.hour = hour;} Public String Getminute () {return minute;} public void Setminute (String minute) {this.minute = minute;} Public String Getsecord () {return secord;} public void Setsecord (String secord) {This.secord = Secord;} @Overridepublic String toString () {return "Timervo [month=" + month + ", day=" + Day + ", week=" + Week + ", hour=" + hour + ", minute=" + minute+ ", secord=" + Secord + "]";}}
public class Timer {private string Name;private string Group;private string expression;private string Jobname;private stri Ng jobgroup;private string Beforeexpression;public string Getbeforeexpression () {return beforeexpression;} public void Setbeforeexpression (String beforeexpression) {this.beforeexpression = beforeexpression;} Public String Getjobname () {return jobName;} public void Setjobname (String jobName) {this.jobname = JobName;} Public String Getjobgroup () {return jobgroup;} public void Setjobgroup (String jobgroup) {this.jobgroup = Jobgroup;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String Getgroup () {return group;} public void Setgroup (String group) {this.group = group;} Public String getexpression () {return expression;} public void SetExpression (String expression) {this.expression = expression;} @Overridepublic String toString () {return "Timer [name=" + name + ", group=" + group + ", expression=" + expression + "]"; }}
Seven, the mapper layer so write
@Repositorypublic interface Timermapper {@Select ("Select T.trigger_name,t.trigger_group,t.job_name,t.job_group, Q.cron_expression from Qrtz_cron_triggers q,qrtz_triggers t where 1=1 and T.trigger_name=q.trigger_name and T.trigger_name=#{name} ") @Results ({@Result property = ' name ', column = ' trigger_name '), @Result (property =" Group " , column = "Trigger_group"), @Result (property = "JobName", and column = "Job_name"), @Result (property = "Jobgroup", C4/>column = "Job_group"), @Result (property = "expression", column = "Cron_expression")}) timer Getcrontrigger (timer timer); @Update ("Update qrtz_cron_triggers set cron_expression = #{expression} where trigger_name = #{name} and Trigger_gr OUP = #{group} ") void Updatebynameandgroup (timer timer);}
Controller is no longer on the code, this is the method call, I believe that everyone is not a problem.
Summarize:
1, the biggest problem is the establishment of the database, the download of the quartz package has SQL script, very pit is in PostgreSQL can not be carried out in one breath.
2, the dependence of the version is finally groping out a set of available, stepping on a lot of pits.
3, cron expression of the week, in fact, usually with the day of the week, for example: every Monday, three per week.
4, online A lot of writing is new to a job, I was in the database first found that task, and then directly update the expression, and then start a task, the wording is somewhat different.
I think so much for the time being.
Springboot2.0+mybatis+postgresql9.6+quartz (Revised version)