spring3创建计划任务

Spring3中加强了注解的使用,其中计划任务也得到了增强,现在创建一个计划任务只需要两步就完成了:

    创建一个Java类,添加一个无参无返回值的方法,在方法上用@Scheduled注解修饰一下;
    在Spring配置文件中添加三个<task:**** />节点;
计划任务类:

/**
 * com.zywang.spring.task.SpringTaskDemo.java
 * @author ZYWANG 2011-3-9
 */
package com.zywang.spring.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * Spring3 @Scheduled 演示
 * @author ZYWANG 2011-3-9
 */
@Component
public class SpringTaskDemo {

	@Scheduled(fixedDelay = 5000)
	void doSomethingWithDelay(){
		System.out.println("I'm doing with delay now!");
	}
	
	@Scheduled(fixedRate = 5000)
	void doSomethingWithRate(){
		System.out.println("I'm doing with rate now!");
	}
	
	@Scheduled(cron = "0/5 * * * * *")
	void doSomethingWith(){
		System.out.println("I'm doing with cron now!");
	}
}


Spring配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
	xmlns:xsi="/2001/XMLSchema-instance" xmlns:task="/schema/task"
	xsi:schemaLocation="/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
	<!-- Enables the Spring Task @Scheduled programming model -->
	<task:executor id="executor" pool-size="5" />
	<task:scheduler id="scheduler" pool-size="10" />
	<task:annotation-driven executor="executor" scheduler="scheduler" />
</beans>



还有一种写法:

package springtest.springtask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 * User: lixiaoming
 * Date: 13-7-31
 * Time: 下午4:09
 * To change this template use File | Settings | File Templates.
 */
@Component
public class SpringJob1 {
    private static Logger logger = LoggerFactory.getLogger(SpringJob1.class);
    public void doJob(){
        logger.info("do job entry");
    }
}


对应的 xml为:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:task="http://www.springframework.org/schema/task"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
              http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd"
       default-lazy-init="true">

    <description>task配置文件</description>

    <!-- namespace 方式 的便捷版 -->
    <task:scheduler id="springScheduler" pool-size="50"/>

    <!-- 开启Spring Task -->
    <task:annotation-driven/>
    <task:scheduled-tasks scheduler="springScheduler">
        <task:scheduled ref="springJob1" method="doJob" fixed-delay="60000"/>
    </task:scheduled-tasks>
</beans>



参考 http://zywang.iteye.com/blog/949123

猜你喜欢

转载自bjmike.iteye.com/blog/1916206