SpringBoot 整合 定时计划与异步

SpringBoot 整合 定时计划与异步

Spring框架分别通过TaskExecutorTaskScheduler接口提供了异步执行和任务调度的抽象

更多的定时与异步的详细内容请看官方文档:scheduling

计划和异步执行的注解

启动计划和异步

@EnableAsync

启用异步执行注解,使用当前注解后,@Async 才能使用异步等处理。

@EnableScheduling

启用定时任务执行注解,使用当前注解后,@Scheduled才能使用执行任务的处理

启动类加入开启定时和异步的注解。

@SpringBootApplication
@EnableAsync//开启异步支持
@EnableScheduling //开启定时任务支持
public class SpringBootTaskIntegratApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootTaskIntegratApplication.class, args);
    }

}

xml配置启动执行

<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
<task:executor id="myExecutor" pool-size="5"/>
<task:scheduler id="myScheduler" pool-size="10"/>

@Async

在方法中使用当前注解,使该方法在调用中异步执行。

 /**
     * 执行睡3秒
     * @Async 异步执行方法,无需等待
     */
    @Override
    @Async
    public void ayanc() {
        try{
            Thread.sleep(3000);
        }catch (Exception e){

        }
    }

这里我们执行调用方法的时候,睡眠3秒,如果没有加@Async那么调用就会等待3秒,加入异步执行后,无需等待3秒,立即执行。

异常管理:实现 AsyncUncaughtExceptionHandler

public class MyAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {

    @Override
    public void handleUncaughtException(Throwable ex, Method method, Object... params) {
        // handle exception
    }
}

@Scheduled

@Scheduled注释以及触发器元数据添加到方法中,然后定时执行:

 /**
     * 每五秒执行一次
     */
    @Override
    @Scheduled(fixedDelay=5000)
    public void hello(){
        System.out.println("进来了吗定时任务");
    }

每五秒钟调用一次以下方法

@Scheduled(fixedRate=5000)
public void doSomething() {
    // something that should run periodically
}

通过指示在第一次执行该方法之前要等待的毫秒数来指定初始延迟

@Scheduled(initialDelay=1000, fixedRate=5000)
public void doSomething() {
    // something that should run periodically
}

定期调度不足以表现出来,则可以提供 cron表达式

@Scheduled(cron="*/5 * * * * MON-FRI")
public void doSomething() {
    // something that should run on weekdays only
}

其他好玩的,请自行读文档,调试开发,实例代码在github上面需要的请自行拉取:spring-boot-integrate
然后后续会集成更多的模块进去,需要请点个star。有问题下方讨论一起学习

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值