(1)Spring.xml 配置
Step1,在 Spring xmls 添加以下代码配置
xmlns:task="http://www.springframework.org/schema/task"
Step2,在 Spring xsi:schemaLocation 中添加以下代码配置
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd
Step3,添加task任务扫描注解配置
<task:executor id="executor" pool-size="5" />
<task:scheduler id="scheduler" pool-size="10" />
<task:annotation-driven executor="executor" scheduler="scheduler" />
Step4,配置注解扫描位置
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<!--根据自定义的包路径设置base-package值,本人配置的扫描位置是com.service-->
<context:component-scan base-package="com.service"/>
(2)com.service包下的定时调度Job接口和实现类如下:
public interface IMyJobService {
public void myJob(); // 注意定时调度方法必须是void型
}
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
@Component
public class MyJobServiceImpl implements IMyJobService {
@Scheduled(cron="15 20 10 * * ?") // 每天10:20:15执行一次
@Override
public void myJob() {
System.out.println("调度任务开始...");
//TODO code实现...
System.out.println("调度任务结束");
}
}
注意:
1,spring的@Scheduled注解 需要写在具体实现上。
2, 定时器的任务方法不能有返回值(如果有返回值,spring初始化的时会报错,具体解决方法可以上网搜查)。
3,实现类上要有组件的注解(如 @Component,@Controller,@Service)。