Spring3.x 注解配置定时任务详解

今天给大家介绍一款非常好用的定时器:spring 3版本的利用注解配置在项目的xml文件中。

1、首先在 spring-config.xml  配置文件头部配置须有:

xmlns:task="http://www.springframework.org/schema/task"

其次xsi:schemaLocation须添加:

http://www.springframework.org/schema/task 
http://www.springframework.org/schema/task/spring-task.xsd

2、spring  扫描过程必须涵盖定时任务类所在的目录:com.xx  属于定时任务类的父级甚至更高级

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

或者可以再详细设置一下:要扫描com.nd包下的所有子类目录,不包含@Controller 相关的文件

<context:component-scan base-package="com.nd">
	    <context:exclude-filter type="annotation"
	        expression="org.springframework.stereotype.Controller" />
</context:component-scan>

3、设置动作启用定时任务:启用注解驱动的定时任务

<task:annotation-driven/>

或者指定定时任务的目录 myScheduler

<task:annotation-driven scheduler="myScheduler"/>

4、配置线程池:可以指定执行线程池的初始大小、最大大小

<task:executor id="executor" pool-size="3" />

调度线程池的大小,调度线程在被调度任务完成前一直运行

<task:scheduler id="myScheduler" pool-size="5"/>

5、项目中java 方法:

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

@Component
public class MyTask {

    @Scheduled(cron = "*/60 * * * * ?")//每隔60秒执行一次
    public void test() throws Exception {
        System.out.println("Test is working......");
    }
    //@Scheduled(cron = "0 0 2 * * ?")//每天凌晨1点整
    //@Scheduled(cron = "0 30 0 * * ?")//每天凌晨0点30分
    //@Scheduled(cron = "0 */60 * * * ?")//1小时处理一次
}

总结:定时器从配置到项目编码都在这,有不懂的地方欢迎留言!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寅灯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值