Spring 定時器
方法一:注解形式
配置文件頭加上如下:
xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
需要 quartz 包
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.2</version> </dependency>
<!-- 掃描包 -->
<context:component-scan base-package="com.hehe.content.job" /> <!-- 啟動定時任務 -->
<task:annotation-driven/>
@Component public class MyTask { @Scheduled(cron="0 0 2 * * ?") // 每天凌晨2點執行,該方法不能有返回值 public void taskCycle(){ System.out.println("======================"); } }
方法二: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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" 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-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"> <!-- 啟動定時任務 --> <!-- <task:annotation-driven/> <context:component-scan base-package="com.hehe.content.job" /> --> <!-- 要調用的工作類 --> <bean id="quartzJob" class="com.hehe.content.job.MyTask"></bean> <!-- 定義調用對象和調用對象的方法 --> <bean id="jobtask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <!-- 調用的類 --> <property name="targetObject"> <ref bean="quartzJob" /> </property> <!-- 調用類中的方法 --> <property name="targetMethod"> <value>taskCycle</value> </property> </bean> <!-- 定義觸發時間 --> <bean id="doTime" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail"> <ref bean="jobtask" /> </property> <!-- cron表達式 --> <property name="cronExpression"> <value>0 0 2 * * ?</value> </property> </bean> <!-- 總管理類 如果將lazy-init='false'那么容器啟動就會執行調度程序 --> <bean id="startQuertz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="doTime" /> </list> </property> </bean> </beans>
問題: 每次任務到點都執行兩次!!!!!!
網上查了好多資料 ,都不是我的情況,后來發現是我的項目在啟動的時候每次都會加載兩次,原來是eclipse 中tomcat配置的問題
圖中若選擇的是第二個,項目會啟動兩次,這就導致了后面的定時器執行了兩次。最后改為了第一選項就好了。
我在騰訊微視玩短視頻 搜索用戶 “lei9527” ,可以相互關注下哈