spring自带的轻量级定时任务

本文介绍如何在 Spring MVC 框架中利用注解形式实现定时任务,无需配置 XML,通过 @Scheduled 注解即可在指定的时间间隔执行特定方法,并提供在 applicationContext.xml 中引入 task 相关内容的示例。

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

以前一直使用Quartz做定时任务,最近开发框架改用spring mvc,原本还打算使用Quartz做定时任务,在网上查资料,发现spring自带定时任务,支持注解形式,非常方便。


以注解形式使用spring定时任务,无需配置XML,只需要在普通的JAVA类中,要进行定时任务的方法前加入@Scheduled注解即可,例如:

    @Scheduled(cron = "0 0/2 8-23 * * ?")   
    public void autoJob() throws Exception {
        // 8点-23点间每隔2分钟定时触发
    }

其中cron的表达式规则和Quartz类似,@Scheduled的其他参数具体可以参考官网文档。


为使定时任务有效,需要在applicationContext.xml中引入task相关的内容,举例如下:

<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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.2.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
       http://www.springframework.org/schema/task
       http://www.springframework.org/schema/task/spring-task-3.2.xsd"
    default-lazy-init="false">
   <!-- 省略了其它内容 --> 
   <task:annotation-driven scheduler="qbScheduler" mode="proxy"/>  
   <task:scheduler id="qbScheduler" pool-size="10"/>
   <!-- 省略了其它内容 --> 

</beans>


至此全部结束,可以测试定时任务了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值