spring自带的轻量级定时任务

以前一直使用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>


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

转载于:https://my.oschina.net/cjkall/blog/195912

猜你喜欢

转载自blog.csdn.net/weixin_34197488/article/details/91756516
今日推荐