Spring task定时任务基于注解和Xml的实现

    关于在spring中应用定时任务,公司之前一直用的是基于 quartz的,xml的配置相当繁琐,后来发现了spring3自带的spring task使用起来非常简单方便,而且功能强大;下面就简单展示一下他的两种实现方式。

一、基于注解@Scheduled()的实现

第一步:建一个定时任务类

在需要执行的方法上面增加注解:@Scheduled(cron=“需要执行的时间参数”)

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
 * Spring基于注解的定时任务类
 * @author zhaoheng
 * 2018-06-22
 */
@Component
public class SpringTaskController {
	private static final Logger logger = Logger.getLogger(SpringTaskController.class);
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    
    /**
      * 定时任务 2秒执行一次
      */
    private static final String times1 = "0/2 * * * * ?";
    /**
      * 每天早上10点半执行一次
      */
    private static final String times2 = "0 30 10 ? * *";
    
    /**
     * 定时任务方法1
     */
	@Scheduled(cron=times1)
	public void teskTest() {
	  
		//logger.info("定时任务开始执行。。。");
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(sdf.format(new Date())+"执行定时任务1执行");
		//logger.info("定时任务执行结束。。。");
	}
	 /**
     * 定时任务方法2
     */
	@Scheduled(cron=times2)
	public void teskTest2() {
		System.out.println(sdf.format(new Date())+"执行定时任务2执行");
	}
}

第二步:新建一个spring-task.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:task="http://www.springframework.org/schema/task"  
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd  
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> 
    
    <!--配置需要扫描的包 (定时任务类所在的包路径)--> 
    <context:component-scan base-package="com.zhh.test.controller">
    	<!-- 不扫描@Controller注解 -->  
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
    </context:component-scan>
    
    <!--启用注解驱动,spring才能识别@Scheduled注解-->
    <task:annotation-driven scheduler="taskScheduler" mode="proxy"/>    
    <!--配置定时任务线程池线程数量, 官方推荐pool-size:5-10 -->
    <task:scheduler id="taskScheduler" pool-size="10"/> 
</beans>

第三步:在spring的配置文件里引入spring-task.xml配置文件

    <!-- 引入spring-task.xml配置文件 -->
    <import resource="spring-task.xml"/>

二、基于Xml配置文件的实现

第一步:新建一个spring-task.xml配置文件


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:task="http://www.springframework.org/schema/task"  
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd  
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> 
    
     <!-- 定义调用对象-->
	<bean id="springTaskXml1" class="com.zhh.test.controller.SpringTaskXmlController"> </bean> 
    <!-- 配置相关类中方法的执行时间-->
    <task:scheduled-tasks scheduler="taskScheduler" > 
        <!-- 每隔 2秒执行一次 -->
    	<task:scheduled ref="springTaskXml1" method="teskTest1" cron="*/2 * * * * ?"/>
    	<!-- 每天凌晨 01:00 执行一次 -->  
        <task:scheduled ref="springTaskXml1" method="teskTest2" cron="0 0 1 * * *"/>  
    </task:scheduled-tasks>
    <!-- 配置线程池线程数量 -->
    <task:scheduler id="taskScheduler" pool-size="5"/> 

</beans>

第二步:建一个定时任务类

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;


/**
 * Spring基于Xml配置 的定时任务类
 * @author zhaoheng
 * 2018-06-22
 */

public class SpringTaskXmlController {
	private static final Logger logger = Logger  
	          .getLogger(SpringTaskXmlController.class);
	
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    /**
     * 定时任务方法1
     */
	public void teskTest1() {
	   
		//logger.info("定时任务开始执行。。。");
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(sdf.format(new Date())+"执行定时任务1执行");
		//logger.info("定时任务执行结束。");
	}
	 /**
     * 定时任务方法2
     */
	public void teskTest2() {
		System.out.println(sdf.format(new Date())+"执行定时任务2执行");
	}
}

第三步:在spring的配置文件里引入spring-task.xml配置文件

    <!-- 引入spring-task.xml配置文件 -->
    <import resource="spring-task.xml"/>

这两种方式实现起来都是非常简单的,在实际的应用中我们可以根据具体的需要来选择使用。

cron表达式

一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。

按顺序依次为
      1 秒(0~59)
      2 分钟(0~59)
      3 小时(0~23)
      4 天(0~31)
      5 月(0~11)
      6 星期(1~7 1为SUN-依次为SUN,MON,TUE,WED,THU,FRI,SAT)
      7.年份(1970-2099)

0 0 10,14,16 * * ? 每天上午10点,下午2点,4点
       0 0/30 9-17 * * ?   朝九晚五工作时间内每半小时
       0 0 12 ? * WED 表示每个星期三中午12点
       "0 0 12 * * ?" 每天中午12点触发
       "0 15 10 ? * *" 每天上午10:15触发
       "0 15 10 * * ?" 每天上午10:15触发
       "0 15 10 * * ? *" 每天上午10:15触发
       "0 15 10 * * ? 2005" 2005年的每天上午10:15触发
       "0 * 14 * * ?" 在每天下午2点到下午2:59期间的每1分钟触发
       "0 0/5 14 * * ?" 在每天下午2点到下午2:55期间的每5分钟触发
       "0 0/5 14,18 * * ?" 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
       "0 0-5 14 * * ?" 在每天下午2点到下午2:05期间的每1分钟触发
       "0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44触发
       "0 15 10 ? * MON-FRI" 周一至周五的上午10:15触发
       "0 15 10 15 * ?" 每月15日上午10:15触发
       "0 15 10 L * ?" 每月最后一日的上午10:15触发
       "0 15 10 ? * 6L" 每月的最后一个星期五上午10:15触发
       "0 15 10 ? * 6L 2002-2005" 2002年至2005年的每月的最后一个星期五上午10:15触发
       "0 15 10 ? * 6#3" 每月的第三个星期五上午10:15触发
       有些子表达式能包含一些范围或列表
       例如:子表达式(天(星期))可以为 “MON-FRI”,“MON,WED,FRI”,“MON-WED,SAT”
       “*”字符代表所有可能的值
       “/”字符用来指定数值的增量
       例如:在子表达式(分钟)里的“0/15”表示从第0分钟开始,每15分钟
                在子表达式(分钟)里的“3/20”表示从第3分钟开始,每20分钟(它和“3,23,43”)的含义一样
       “?”字符仅被用于天(月)和天(星期)两个子表达式,表示不指定值
       当2个子表达式其中之一被指定了值以后,为了避免冲突,需要将另一个子表达式的值设为“?”
       “L” 字符仅被用于天(月)和天(星期)两个子表达式,它是单词“last”的缩写
       如果在“L”前有具体的内容,它就具有其他的含义了。例如:“6L”表示这个月的倒数第6天
       注意:在使用“L”参数时,不要指定列表或范围,因为这会导致问题
       W 字符代表着平日(Mon-Fri),并且仅能用于日域中。它用来指定离指定日的最近的一个平日。
       大部分的商业处理都是基于工作周的,所以 W 字符可能是非常重要的。
假如15号是星期六,那么 trigger 会在14号(星期五)触发,因为星期四比星期一离15号更近。
       C:代表“Calendar”的意思。它的意思是计划所关联的日期,如果日期没有被关联,则相当于日历中所有日期。

这里的cron表达式也是参考网络上的文章进行总结的,需要更详细的请百度和Google。

猜你喜欢

转载自blog.csdn.net/muscleheng/article/details/80769884