因为最近用到定时任务的功能,因此用到了spring的定时任务,配置方式如下
1.新建一个spring-scedul.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:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置任务扫描-->
<task:annotation-driven />
<context:component-scan base-package="com.hfs.modules.schedul"></context:component-scan>
<!-- 扫描任务 -->
</beans>
2.在springMVC.xml中引入spring-scedul.xml
<import resource="classpath:spring-scedul.xml"/>(应该由web.xml去加载)
3、创建任务类
@Component
public class weatherTask {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
@Scheduled(cron = "0/5 * * * * ? ") // 每隔5秒执行
public void taskCycle() {
logger.info("------每隔5秒执行---------");
}
结果:项目启动时每次执行定时任务都会执行两次。
然后百度一大堆感觉不靠谱。。。
可能是因为项目启动时配置文件被加载了两次,将上面的2步骤改为在web.xml中配置加载spring-scedul.xml文件,如下:
<!-- 加载Spring配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring-context.xml,classpath:spring-schedul.xml</param-value>
</context-param>
结果发现启动时报错:Configuration problem: Only one AsyncAnnotationBeanPostProcessor may exist within the context
意思是有重复加载的bean
解决方案:将spring-scedul.xml中的 <task:annotation-driven />给干掉,问题就解决了,定时任务不会被加载两次了。