Spring MVC使用Schedule實現定時任務

Schedule存在spring-context.jar包中。java

實現簡單步驟:git

一、配置bean.xml開啓定時任務支持。github

<?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:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="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.xsd 
                             http://www.springframework.org/schema/mvc 
                             http://www.springframework.org/schema/mvc/spring-mvc.xsd 
                             http://www.springframework.org/schema/task  
                           http://www.springframework.org/schema/task/spring-task.xsd ">

    <!-- 開啓定時任務 --> <task:annotation-driven />

    <context:component-scan base-package="com.jsoft.testspring" />

    <context:annotation-config />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
    
</beans>

代碼實現:web

package com.jsoft.testspring.testmvchelloworld;

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

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

@Component public class ScheduleTest {  

    @Scheduled(cron = "0/5 * * * * ?")  
    public void schTest1() {  
        Date date = new Date();  
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        String dateStr = sim.format(date);  
        System.out.println("這是spring定時器1,每五秒執行一次,當前時間:" + dateStr);  
    }  
}  

注意要加@Component這類的註解。spring

示例工程:https://github.com/easonjim/5_java_example/tree/master/springtest/test24/testmvchelloworldspring-mvc

 

參考:mvc

http://blog.csdn.net/tuzongxun/article/details/51576301jsp

相關文章
相關標籤/搜索