Spring整合Quartz (cronTrigger和simpleTrigger实现方法)
之前有记录过一次springboot整合Quartz的文章,由于偶尔一次自己使用spring需要整合Quartz时有遇到一些异常,导致定时job无法正常执行,所以在此也记录一下spring整合quartz的两种实现方式。SpringBoot整合Quartz
应用框架版本
Spring 5.1.4.RELEASE
Quartz 2.3.0
Maven 3.5.0
Demo目录结构
web.xml配置
/p>
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
contextConfigLocation
classpath:spring.xml
org.springframework.web.context.ContextLoaderListener
index.jsp
Spring.xml配置
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
run
0/1 * * * * ?
pom.xml依赖
在使用quartz版本时需要注意与spring的版本对应。
spring 3.0版本内置的是Quartz<2.0的版本,所以在使用Spring 3.0版本以上时,需要使用Quartz 2.0以上的版本
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
spring-quartz
com.test.quartz
1.0-SNAPSHOT
war
com.test.quartz Maven Webapp
http://www.example.com
UTF-8
1.7
1.7
5.1.4.RELEASE
2.3.0
junit
junit
4.11
test
org.springframework
spring-context
${spring.version}
commons-logging
commons-logging
org.springframework
spring-context-support
${spring.version}
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-orm
${spring.version}
jar
compile
org.springframework
spring-test
${spring.version}
jar
test
org.quartz-scheduler
quartz
${quartz.version}
com.test.quartz
maven-clean-plugin
3.1.0
TimerTask.java
package com.test.quartz.timer;
import com.test.quartz.service.TaskService;
/**
* @author yd
* @date 2019-06-11 16:08
* @describe 定时job1
*/
public class TimerTask {
private TaskService taskService;
public TaskService getTaskService() {
return taskService;
}
public void setTaskService(TaskService taskService) {
this.taskService = taskService;
}
public void run(){
String process = taskService.process(this.getClass().getSimpleName());
System.out.println(process);
}
}
TimeTask2.java
package com.test.quartz.timer;
import com.test.quartz.service.TaskService;
/**
* @author yd
* @date 2019-06-11 16:28
* @describe 定时job2
*/
public class TimeTask2 {
private TaskService taskService;
public TaskService getTaskService() {
return taskService;
}
public void setTaskService(TaskService taskService) {
this.taskService = taskService;
}
public void run(){
String process = taskService.process(this.getClass().getSimpleName());
System.out.println(process);
}
}
service
在对quartz集成的同时,在这里也引入了service层的注入,demo中只是一个简单的样例,可以根据自己的实际需求去对service层进行编辑。
TaskService.java
package com.test.quartz.service;
import org.springframework.stereotype.Service;
/**
* @author yd
* @date 2019-06-11 16:11
* @describe 文件描述
*/
@Service
public class TaskService {
public String process(String taskname){
return this.getClass().getSimpleName()+"在处理任务:"+taskname;
}
}
执行结果