Spring配置文件xmlns加入
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation中加入
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"
spring扫描注解的配置
<context:component-scan base-package="com.test"/>
任务扫描注解
<task:executor id="executor" pool-size="5" /> <task:scheduler id="scheduler" pool-size="10" /> <task:annotation-driven executor="executor" scheduler="scheduler" />
类:
@Component
public class TestScheduled {
@Scheduled(cron="0/5 * * * * ? ")
public void test(){
System.out.println("this is test shecdule");
}
}
注意: 本人在刚开始测试时,定时任务不执行,查了springmvc的配置才发现:
<context:component-scan base-package="com.testm" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
在配置中使用了 use-default-filters 这个的默认属性是true,默认自动扫描带有@Component、@Repository、@Service和@Controller的类。而我配置成了false,所以没有执行注解类为@Component的定时任务。改为以下方式即可:
<context:component-scan base-package="com.testm" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/>
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
把Component注解加入扫描的范围即可。