第一種:spring自帶的定時任務功能
一)在xml里加入task的命名空間
xmlns:task="http://www.springframework.org/schema/task" http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd
(二)啓用註解驅動的定時任務
<task:annotation-driven scheduler="myScheduler"/>
(三)配置定時任務的線程池(多任務時需要進行配置)
配置線程池,若不配置多任務下會有問題。後面會詳細說明單線程的問題。
<task:scheduler id="myScheduler" pool-size="5"/>
(四)任務類
@Component("regularTasks")
public class RegularTasks {
@Resource
private ContractManager contractManager;
@Resource
private PayDetailsManager payDetailsManger;
/*@Scheduled(fixedRate = 1000 * 5) //心跳更新。啓動時執行一次,之後每五秒執行一次
public void updateContractPayStatus() {
}*/
}
上面是spring的註解方式搞的定時任務。
第二種:spring結合quartz配置定時任務
(一)依賴:
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
</dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
</dependency>
(二)配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Timer schedule -->
<!-- 總管理類如果將lazy-init='false'那麼容器啓動就會執行調度程序 -->
<bean id="startQuertz" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" lazy-init="false" >
<property name="triggers">
<!-- 作業調度器,list下可加入其他的調度器 -->
<list>
<ref bean="sendMessageTrigger" />
</list>
</property>
<property name="autoStartup" value="true"/>
</bean>
<!-- start 輪巡發送信息-->
<bean id="sendMessageJobBean" class="com.biz.timeTask.TimeTask"/> <!-- 任務類 -->
<bean id="sendMessageJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!-- 調用的類 -->
<property name="targetObject" ref="sendMessageJobBean" />
<!-- 調用類中的方法 -->
<property name="targetMethod" value="execute" />
<!-- 將併發設置爲false -->
<property name="concurrent" value="false" />
</bean>
<bean id="sendMessageTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="sendMessageJobDetail" />
<property name="cronExpression" value="0 0/10 * * * ?" /><!-- 0 0/60 * * * ? 0 0 12 * * ?-->
</bean> <!-- 這個value是寫入執行時間表達式的 -->
<!-- end 輪巡發送信息-->
</beans>
(三)任務類
public class TimeTask {
public void execute() {
}
}