Spring MVC使用Schedule实现定时任务

本文介绍如何在Spring框架中配置并实现定时任务。通过在bean.xml文件中启用定时任务支持,并使用@Component注解标记定时任务类,可以轻松实现定时执行的方法。文中还提供了具体的XML配置示例和Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.youkuaiyun.com/tuzongxun/article/details/51576301

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值