zoukankan      html  css  js  c++  java
  • Spring MVC使用Schedule实现定时任务

    Schedule存在spring-context.jar包中。

    实现简单步骤:

    1、配置bean.xml开启定时任务支持。

    <?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>

    代码实现:

    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这类的注解。

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

    参考:

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

  • 相关阅读:
    NDOC中文支持及入门用法
    网页代码常用小技巧
    SOCKET通讯点滴
    自动备份程序目录
    MySql.Data.dll Microsoft.Web.UI.WebControls.dll下载
    c#:获取IE地址栏中的URL
    比较好的单例登录模式(参考网友)
    FreeTextBox使用详解
    2005自定义控件显示基准线
    连接字符串大全
  • 原文地址:https://www.cnblogs.com/EasonJim/p/7820280.html
Copyright © 2011-2022 走看看