spring-task简单实用小结

spring-task,是spring 3.0以后自带的定时任务工作机制,可以将它看成一个轻量级的Quartz,使用起来比Quartz简单的多,并且不需要引用额外的jar包

首先编写我们的任务类,就是普通的java类,不用继承或实现其它类

并且增加如下spring 配置信息
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/fex
        http://www.springframework.org/schema/fex/spring-fex-1.5.xsd
        http://www.springframework.org/schema/task 
        http://www.springframework.org/schema/task/spring-task-3.1.xsd 
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd"
        >

	<!-- 定时任务声明 -->

	<task:executor id="executor" pool-size="5" />
	<task:scheduler id="scheduler" pool-size="10" />

	<task:annotation-driven executor="executor" scheduler="scheduler" />
	<!-- Spring定时器注解开关-->  
  <!--   <task:annotation-driven />   -->
    <!-- 此处对于定时时间的配置会被注解中的时间配置覆盖,因此,如需要配置就不要再使用注解 -->  
    <task:scheduled-tasks scheduler="scheduler">  
    	<!-- 每天晚上1点执行 -->
<span style="white-space:pre">	</span><!-- ref对应的是任务类的注解名称  method对应执行任务的方法 -->
        <task:scheduled ref="testTask" method="testTaskMethod" cron="0 0 1 * * ?"/>  
    </task:scheduled-tasks>  
	

	<!-- 定时任务扫描的目录 -->
	<context:component-scan base-package="com.test.task" />

如上配置,配置文件如果定义了任务的执行时间,则不需要通过注解的方式在代码中定义,详见代码中16行注释部分。
如果完全使用注解的话则可以去掉
<task:scheduled-tasks scheduler="scheduler"> 该部分配置



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章