写项目时遇到需要使用quartz,使用注解标记一个定时任务是发现,每个任务都会执行两次。
项目中使用注解方式使用定时任务:
@Log4j
@Component
public class TKGGZHMessageJob {
/**
* 每2分钟执行一次
*/
@Scheduled(cron = "0 0/2 * * * ?")
public void message() {
log.info("执行 TKGGZHMessageJob " + new Date().toLocaleString());
}
}
运行时出现以下问题:
原因:
在web.xml 中
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:spring/applicationContext.xml
</param-value>
</init-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value> classpath*:spring/applicationContext.xml</param-value>
</context-param>
由于在这里声明了两次applicationContext.xml,导致定时任务加载两次。
解决办法:
将init-param 和 context-param 的配置文件分开。
比如:
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/initparam.xml
</param-value>
</init-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value> classpath*:spring/applicationContext.xml</param-value>
</context-param>
附:<init-param> 和 <context-param> 解析
https://blog.csdn.net/q_l_s/article/details/51919072
2018-11-06更新
再次使用定时任务,并且按照上述配置文件进行编写,但是还是会出现执行两次的情况。原因还是因为配置错误的问题,故把定时任务的配置文件单独放在一个配置文件中,然后在web.xml中声明。
新增定时配置文件:taskConfig.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:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
<!-- 注解定时任务 -->
<task:annotation-driven/>
</beans>
web.xml配置
{{ cmt.username }}
{{ cmt.content }}
{{ cmt.commentDate | formatDate('YYYY.MM.DD hh:mm') }}