SpringFramework

spring定时任务

2017-11-15  本文已影响100人  江江的大猪

spring定时任务

spring提供了异步执行和任务调度的功能,可以简化程序员的工作。这两种功能在spring中是放在一起讲的,很容易看晕,网上的文章也很少有分开讲的,在这里只讲任务调度也就是定时任务的使用方式。可以直接看官方文档34. Task Execution and Scheduling章节。

本文基于spring4.x,xml配置方式,java config用不惯啊...java config配置的方式直接看上面的spring官方文档对应找吧
<!--在xml中引入task命名空间-->
<beans 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">
       <!--开启任务调度的注解驱动,并设置任务调度使用的调度器-->
       <!--不设置scheduler默认使用大小为1的线程池-->
       <task:annotation-driven scheduler="myScheduler"/>
       <!--任务调度的调度器只接受一个线程池的线程数,默认是1-->
       <task:scheduler id="myScheduler" pool-size="10"/>
</beans>
@Component
public class SpringTaskDemo {
    //Scheduled注解还有几种设置定时任务的属性,点进去看源码或者百度谷歌,资料很多
    @Scheduled(fixedDelay = 1000)
    public void task() {
        System.out.println("spring scheduled task run");
    }
}
<task:scheduler id="myScheduler" pool-size="10"/>
<task:scheduled-tasks scheduler="myScheduler">
    <task:scheduled ref="beanA" method="methodA" fixed-delay="5000" initial-delay="1000"/>
    <task:scheduled ref="beanB" method="methodB" fixed-rate="5000"/>
    <task:scheduled ref="beanC" method="methodC" cron="*/5 * * * * MON-FRI"/>
</task:scheduled-tasks>

spring的定时任务是一种抽象,即支持jdk,也可以使用第三方开源工具Quartz,timer有关的内容可以看多线程基础中对应的部分

肥肥小浣熊
上一篇 下一篇

猜你喜欢

热点阅读