启动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());
}
}