Spring @Scheduled应用解析

     最近,遇到的一个需求,需要执行定时任务,每个一定时间需要执行某个方法

     因为项目是SpringMVC的项目,所以使用的是Spring @Scheduled(由于quartz应用起来太麻烦,所以没有采用)

     接下来是应用步骤:

    1、配置文件

    1.1 需要配置一项  xmlns 如下:

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

    1.2 配置 xsi:schemaLocation(在applicationContext.xml中的beans属性) 

http://www.springframework.org/schema/task  
http://www.springframework.org/schema/task/spring-task-4.1.xsd     

 1.3 配置扫描  (在applicationContext.xml中的beans标签内) 

<!-- 定时器 注解 -->
<task:annotation-driven />

 1.4 配置扫描路径,做了定时总得让Spring扫描到,对吧

<!-- 包的扫描路径配置 -->
<context:component-scan base-package="com.wl"> <context:exclude-filter type="regex" expression=".common.*" /> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan>

 

 1.5 创建任务类

 类要加上@Component注解,Spring才能扫描到,另外fixedRate  和 fixedDelay 区别加在注释上了

@Component
public class Task  {
	
	/**
	 * 每隔5分钟执行
	 */
	@Scheduled(fixedRate = 1000*300) 
	public void task1(){
		
		// do!
		
	}
	/**
	 * 上一个任务执行结束后5分钟,再执行下一个任务
	 */
	@Scheduled(fixedDelay = 1000*300) 
	public void task2(){
		
		// do!
		
	}
	/**
	 * 上一个任务执行结束后5分钟,再执行下一个任务
	 */
	@Scheduled(fixedDelay = 1000*300) 
	public void task2(){
		
		// do!
		
	}
        /**
	 * 每隔5分钟执行
	 */
     @Scheduled(cron = 0 0/5 * * * ? ) 
     public void task3(){ // do! }
}

  

附赠cron格式在线生成器

http://cron.qqe2.com/
posted @ 2016-12-05 16:41  马三  阅读(2460)  评论(0编辑  收藏  举报