Spring3 Shedule Task之注解实现 (两次启动Schedule Task 的解决方案)

  • Post author:
  • Post category:其他


在spring3 中的新引入的task 命名空间。可以部分取代 quartz 功能,配置和API更加简单,并且支持注解方式。但是如果需要使用比较复杂的任务调度。还是建议使用quartz。


第一步:

在Spring的相关配置文件中(applicationContext.xml或者是{project_name}_servelt.xml或者是独立的配置文件如XXX_quartz.xml)中配置并开启Spring Schedule Task.注意其中高亮的部分是必须的。

<?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:tx=”http://www.springframework.org/schema/tx”

xmlns:context=”http://www.springframework.org/schema/context”

xmlns:mvc=”http://www.springframework.org/schema/mvc”

xmlns:p=”http://www.springframework.org/schema/p”


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/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd

http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd


http://www.springframework.org/schema/task



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


“>

<mvc:annotation-driven />

<context:component-scan base-package=”com.mytools.validator.engine” />

<!– 启动定时器 –>


<task:annotation-driven/>


</beans>


第二步:

可以在类中的需要定时执行的方法下指定如下Annotation

@Scheduled(cron=”0 33/3 * * * ?”) //每小时的33分钟开始执行,每3分钟执行1次

public void start() throws ServletException {


validate();

}

备注:其实@Scheduled中可以指定如下3中时间表达式:

(1)fixedRate:每隔多少毫秒执行一次该方法。如:


@Scheduled(fixedRate=2000)  // 每隔2秒执行一次

public void scheduleMethod(){

System.out.println(“Hello world…”);

}

(2)fixedDelay:当一次方法执行完毕之后,延迟多少毫秒再执行该方法。

(3)cron:详细配置了该方法在什么时候执行。cron值是一个cron表达式。如:


@Scheduled(cron=”0 0 0 * * SAT”)

public voidarchiveOldSpittles() {

// …

}


到指定时间后,任务总是执行2次的解决方案:

这是因为我们很容易在一个基于Spring的Web工程中启动2个定时线程:

第一次:web容器启动的时候,读取applicationContext.xml(或者别的Spring核心配置文件)文件时,会加载一次。


第二次:Spring本身会加载applicationContext.xml(或者别的Spring核心配置文件)一次。

解决方案:将你的Task的相关配置独立出来并在web.xml中通过context-param加载。而不是通过spring加载。

1) 独立出Spring-Task,如新命名一个文件名叫cms_quartz.xml

2)    在web.xml中去加载该文件:

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>/WEB-INF/cms-servlet.xml,

classpath:cms-quartz.xml</param-value>


</context-param>