您的位置:首页 > 编程语言 > Java开发

使用spring @Scheduled注解执行定时任务

2017-01-18 11:09 375 查看
首先要配置我们的spring.xml

xmlns 多加下面的内容

1 xmlns:task="http://www.springframework.org/schema/task"


然后xsi:schemaLocation多加下面的内容

1 http://www.springframework.org/schema/task 2 http://www.springframework.org/schema/task/spring-task-3.1.xsd[/code] 
最后是我们的task任务扫描注解

1 <task:annotation-driven/>


我的配置扫描位置是

1 <context:annotation-config/>
2 <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
3 <context:component-scan base-package="com.test"/>


扫描的是com.test这样的包下的内容

下面需要接口和实现(我的这几个java文件都是com.test的包下的

public interface IMyTestService {
public void myTest();
}


1 @Component  //import org.springframework.stereotype.Component;
2 public class MyTestServiceImpl  implements IMyTestService {
3       @Scheduled(cron="0/5 * *  * * ? ")   //每5秒执行一次
4       @Override
5       public void myTest(){
6             System.out.println("进入测试");
7       }
8 }


需要注意的几点:

1、spring的@Scheduled注解  需要写在实现上

2、 定时器的任务方法不能有返回值(如果有返回值,spring初始化的时候会告诉你有个错误、需要设定一个proxytargetclass的某个值为true、具体就去百度google吧)

3、实现类上要有组件的注解@Component
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: