由于项目中夜间需要更新数据库,人为无法完成。所以使用job来解决这一问题。
原理:将job交由Spring管理,当服务器启动后定时的执行我们的代码段即可。
Spring管理Job:
可以直接配置在spring-ApplicationContext.xml中,也可以单独建一个spring-context-quartz.xml与Spring的AOP【事务等】相关配置分离。项目中采用后者。
<?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:websocket="http://www.springframework.org/schema/websocket"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!--要调度的对象-->
<bean id="jobBean" class="com.bonc.ioc.lmp.quartz.RedisCacheManager" />
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="jobBean"/>
<property name="targetMethod" value="execute"/><!-- 执行"jobBean"中的execute方法 -->
<property name="concurrent" value="false"/><!--将并发设置为false-->
</bean>
<bean id="trigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"><!-- 定义 Job 何时执行 -->
<property name="jobDetail" ref="jobDetail" />
<property name="cronExpression" value="0/3 * * * * ?" />
</bean>
<!-- <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="job1" />
<property name="startDelay" value="0" />调度工厂实例化后,经过0秒开始执行调度
<property name="repeatInterval" value="3000" />每3秒调度一次
</bean> -->
<!-- 总管理类如果将lazy-init='false'那么容器启动就会执行调度程序 -->
<bean id="startQuertz" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" lazy-init="false" >
<property name="triggers">
<list>
<ref bean="trigger" /><!--作业调度器,list下可加入其他的调度器-->
</list>
</property>
</bean>
</beans>
上文中的<bean id="jobBean" class="com.bonc.ioc.lmp.quartz.RedisCacheManager" />,中的id自己随便起,关联的类是项目中执行job的类。
jobBean方法类:
package com.bonc.ioc.lmp.quartz;
public class RedisCacheManager {
/**
* 同步redis的缓存数据导数据库
*/
public void execute() {
System.out.println("每隔三秒执行这个方法。");
}
}
web.xml中注册:
<!-- 配置Spring配置文件路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/spring-context*.xml</param-value>
</context-param>
启动项目:
配置完成job就可以定时执行了,这里只是基本启动和配置,具体的业务逻辑替换RedisCacheManager类中的execute()方法就行了。或者再注册一个job,执行多个任务。配置文件中的list标签下增加即可。