Spring @Scheduled 注解实现定时器调度配置

(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)。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值