SpringBoot 整合 定时计划与异步
Spring框架分别通过TaskExecutor
和TaskScheduler
接口提供了异步执行和任务调度的抽象
更多的定时与异步的详细内容请看官方文档: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。有问题下方讨论一起学习