项目主要配置及代码如下,但是启动服务后,一直没执行这个方法,不知什么原因。请指点
package com.yl.reqPos;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@Lazy(false)
public class Singer {
@Scheduled(cron ="0/5 * * * * *") //第二种方式
public void singing(){
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(sdf.format(date));
}
}
applicationContext-jobs.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd"
default-lazy-init="false">
<context:component-scan base-package="com.yl.reqPos.*" />
queue-capacity="500" rejection-policy="CALLER_RUNS" />
首先要配置spring.xml
xmlns 多加下面的内容、
[html] view plaincopy
xmlns:task="http://www.springframework.org/schema/task"
然后xsi:schemaLocation多加下面的内容、
[html] view plaincopy
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd
最后是我们的task任务扫描注解
[html] view plaincopy
<task:annotation-driven/>
我的配置扫描位置是:
[html] view plaincopy
<context:annotation-config/>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<context:component-scan base-package="com.test"/>
扫描的是com.test这样的包下的内容、
下面需要接口和实现(我的这几个Java文件都是com.test的包下的、
[java] view plaincopy
public interface IMyTestService {
public void myTest();
}
[java] view plaincopy
@Component //import org.springframework.stereotype.Component;
public class MyTestServiceImpl implements IMyTestService {
@Scheduled(cron="0/5 * * * * ? ") //每5秒执行一次
@Override
public void myTest(){
System.out.println("进入测试");
}
}
执行后控制台就会打印出 进入测试 了
需要注意的几点:
1、spring的@Scheduled注解 需要写在实现上、
2、 定时器的任务方法不能有返回值(如果有返回值,spring初始化的时候会告诉你有个错误、需要设定一个proxytargetclass的某个值为true、)
3、实现类上要有组件的注解@Component
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。