配置方式
- 配置文件中添加命名空间 xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd - 添加扫描包;和注解
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 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/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <!-- 新闻的service --> <!-- <bean id="newsService" class="com.ssm.service.impl.NewsServiceImpl" /> --> <!-- 配置扫描--> <context:component-scan base-package="com.ssm.service.*"></context:component-scan> <context:annotation-config /> <task:annotation-driven/>//使用的注解方式来实现Spring的定时任务 <!-- 开启这个配置,spring才能识别@Scheduled注解 --> <<task:annotation-driven scheduler="qbScheduler" mode="proxy"/> <task:scheduler id="qbScheduler" pool-size="10"/> </beans>
3.定时任务 注意在扫描包下
-
package com.ssm.service.task; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; @Component("spider") public class Spider { @Scheduled(fixedRate=10*1000) public void getNews(){ System.out.println(new Date()+"-------getNews"); } }
全注解方式
- 使用两个注解@EnableScheduling@Scheduled
- 定时任务也要在扫描包下
@Component @EnableScheduling public class Spider { @Scheduled(fixedRate=10*1000) public void getNews(){ System.out.println(new Date()+"-------getNews"); } }