啟動spring定時任務執行兩次的解決辦法
1、需要把定時任務配置單獨添加在一個xml配置檔案中,application-task.xml(示例配置為啟動項目後執行一次定時任務)
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<!-- 定時任務 -->
<bean id="myScheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="simpleTriggerBean"></ref>
</list>
</property>
<!--<property name="autoStartup" value="true"></property>-->
</bean>
<bean id="myJobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="quartzTaskJob"/>
<property name="targetMethod" value="testJob"/>
<property name="concurrent" value="false" />
<!-- 是否允許任務并發執行。當值為false時,表示必須等到前一個線程處理完畢後才再啟一個新的線程 -->
</bean>
<bean id="simpleTriggerBean" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail" ref="myJobDetail"/>
<property name="repeatInterval" value="0"/>
<property name="repeatCount" value="0"/>
<property name="startDelay" value="5000"/> <!-- 啟動項目後延遲5s執行定時任務-->
</bean>
<!-- 定時器開關 -->
<task:annotation-driven/>
<bean id="quartzTaskJob" class="com.tfrd.task.QuartzTaskJob"></bean>
</beans>
2、在web.xml的contextConfigLocation中添加該配置檔案
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml,/WEB-INF/application-task.xml</param-value>
</context-param>
public class QuartzTaskJob {
/**
* 定時任務
*/
//@Scheduled(cron = "0 0/5 * * * ?")
public void testJob() {
System.out.println("執行定時任務" + LocalDateTime.now());
}
}