Spring注解@Scheduled定时任务
一、首先配置applicationContext-task.xml
(1)添加 xmlns:task="http://www.springframework.org/schema/task"
(2)添加 xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"
------- applicationContext-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:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"> <description>spring task定时任务</description> <!-- 定时任务配置 scheduler 方式 注解 --> <context:component-scan base-package="com.lwj.task" /> <task:executor id="executor" pool-size="5" /> <task:scheduler id="scheduler" pool-size="10" /> <task:annotation-driven executor="executor" scheduler="scheduler" /> </beans>
二、配置applicationContext.xml文件
------- applicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <!-- 开启注解扫描 --> <context:annotation-config /> <!--引入配置属性文件 --> <context:property-placeholder location="classpath:config.properties" /> <!--自动扫描含有@Service将其注入为bean 和@Repository注入 --> <context:component-scan base-package="com.lwj.service,com.lwj.dao" /> <!-- 定时任务 --> <import resource="applicationContext-task.xml" /> </beans>
三、编写TimeTask.java
------- TimeTask.java文件 --------
package com.lwj.task; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * * @Description : 定时任务 * @author : lwj * @version : 1.0 * @Date : 2016年4月7日 上午8:56:00 */ @Component public class TimeTask { @Scheduled(cron="0/10 * * * * *") public void Test(){ System.out.println("每10秒执行一次任务!"); } }
效果图: