zoukankan      html  css  js  c++  java
  • 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/
  • 相关阅读:
    NOI-01:查找最接近的元素 基本二分
    C#学习笔记之——数据库操作的相关类
    Lua学习笔记——环境安装(Windows和MacOS)和在MacOS安装时错误解决方法
    Ubuntu下对数据库的操作
    Git常用操作
    [Unity游戏开发]常用类之Time类
    [Unity游戏开发]四元数Quaternion
    [Unity游戏开发]常用类之Transform类
    [Unity游戏开发]常用类之Component类
    [Unity游戏开发]射线(Ray)
  • 原文地址:https://www.cnblogs.com/maxm/p/5987595.html
Copyright © 2011-2022 走看看