问题背景
有时候后端服务的数据是来自第3方接口, 需要我们定时拉取第3方接口的数据到本地服务, 我们可以使用Quartz来创建定时任务, 定时拉取数据
创建步骤
1.导包
需要的jar包包括
quartz-2.2.1.jar
aopalliance-1.0.jar
commons-logging-1.2.jar
spring-aop-4.3.1.RELEASE.jar
spring-beans-4.3.1.RELEASE.jar
spring-context-4.3.1.RELEASE.jar
spring-core-4.3.1.RELEASE.jar
spring-expression-4.3.1.RELEASE.jar
2.创建需要执行的任务类
public class TestJob {
private static void updateData() {
System.out.println("任务执行了");
}
}
3.创建配置文件spring-auqrtz.xml, 配置定时任务
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- 要调用的工作类 -->
<bean id="testJob" class="com.aisi.test.timer.TestJob" />
<!-- 定义调用对象和调用对象的方法 -->
<bean id="testJobTask"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!-- 调用的类 -->
<property name="targetObject">
<ref bean="testJob" />
</property>
<!-- 调用类中的方法 -->
<property name="targetMethod">
<value>updateData</value>
</property>
</bean>
<!-- 定义触发时间 -->
<bean id="testJobTime"
class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail">
<ref bean="testJobTask" />
</property>
<!-- cron表达式 -->
<property name="cronExpression">
<value>0 */1 * * * ?</value>
</property>
</bean>
<!-- 秒 分 时 日 月 周
每隔5秒钟执行一次:*/5 * * * * ?
每隔1分钟执行一次:0 */1 * * * ?
每隔1小时执行一次: 0 * */1 * * ?
每天23点执行一次:0 * 23 * * ?
每天10:15执行一次: 0 15 10 * * ? -->
<!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序 -->
<bean id="startQuertz" lazy-init="false" autowire="no"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="testJobTime" />
</list>
</property>
</bean>
</beans>
4.将配置文件spring-quartz.xml配置到web.xml中
此处使用classpath:spring-*来匹配多个配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<!-- 当监听器被触发以后加载Spring的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-*</param-value>
</context-param>
...
<listener>
<description>spring监听器</description>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
...
</web-app>
5.启动服务, 定时任务开始定时执行, 每分钟执行一次
可以通过定时任务, 定时拉取其他平台的数据到本地服务
参考资料:
https://www.cnblogs.com/kay/archive/2007/11/02/947372.html