使用Spring自帶的定時執行任務工具執行任務
1.首先寫一個任務類:
@Component("taskJob")
public class DeleteTableRecord {
@Scheduled(cron = "0 0 3 * * ?")
public void job() {
System.out.println("正在執行任務....");
//要執行的任務
System.out.println("任務執行完成.");
}
}
@Scheduled(cron = "0 0 3 * * ?")表示在每天凌晨三點執行任務
@Scheduled(cron = "0 15 3 * * ?")表示每天凌晨三點十五分執行任務
2.在Spring配置檔案中加入如下配置:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"
<context:annotation-config />
<!-- 掃描Task所在包-->
<context:component-scan base-package="com.mis.task" />
<!-- Spring支援@Scheduled註解 -->
<task:annotation-driven scheduler="qbScheduler" mode="proxy" />
<!--Task的配置-->
<task:scheduler id="qbScheduler" pool-size="1" />
<bean>
...
</bean>
</beans>