1. 程式人生 > >spring-task-01

spring-task-01

第一種方式

package cn.mldn.util;
import java.text.SimpleDateFormat;

public class MyTask2 {
    public void runJob() {
        System.out.println("*** [當前日期時間]" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new java.util.Date()));
    }
}

applicationContext

    <bean id="myTask" class
="cn.mldn.util.MyTask2" /> <task:scheduled-tasks> <!-- <task:scheduled ref="myTask" method="runJob" fixed-rate="2000"/> --> <task:scheduled ref="myTask" method="runJob" cron="0 * * * * ?"/> </task:scheduled-tasks>

第二種方式

package cn.mldn.util;

import
java.text.SimpleDateFormat; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class MyTask2 { //@Scheduled(fixedRate=2000) //間隔觸發 @Scheduled(cron="0 * * * * ?") public void runJob() { System.out.println("*** [當前日期時間]" + new
SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new java.util.Date())); } }
<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd">
    
    <!-- 表示現在啟用Annotation配置,配置的只能夠是任務 -->
    <task:annotation-driven/>
    <task:scheduler id="myScheduler" pool-size="20"/> <!-- 表示多個任務彼此之間的延遲不會影響 -->
    <context:annotation-config />
    <context:component-scan base-package="cn.mldn" />
    
</beans>