Spring 定时任务@Scheduled 与异步@Async及线程池配置

简介

使用@Scheduled时,默认是单线程线程,spring中默认的配置如下,

 这样的话,在使用@Scheduled时,其实都是单线程去执行的,我们可以使用@Async来使用线程池进行异步的调度。

自定义线程池:

// 名字必须是 taskExecutor
@Bean(name = "taskExecutor")
    ThreadPoolTaskExecutor taskExecutor(TaskExecutorBuilder builder) {
        ThreadPoolTaskExecutor taskExecutor = builder.build();
        taskExecutor.setThreadNamePrefix("interface-handle-thread-");
        return taskExecutor;
    }

测试:

 

可以看到使用@Async注解的已经应用了线程池配置,没有用的还是之前的单线程

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 @Scheduled 注解中添加 @Async 注解可以实现定时任务异步执行。@Async 注解可以用于标记一个方法为异步方法,表示该方法将在一个独立的线程中执行,而不会阻塞当前线程。 下面是一个示例: ```java import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class MyScheduledTask { @Async @Scheduled(fixedRate = 5000) // 每隔5秒执行一次 public void myAsyncTask() { // 异步执行的任务逻辑 System.out.println("异步任务开始执行..."); // ... System.out.println("异步任务执行完成!"); } } ``` 在上述示例中,我们在定时任务方法上同时添加了 @Async 和 @Scheduled 注解。@Scheduled 注解用于配置定时任务的执行频率,这里使用 fixedRate 表示每隔5秒执行一次。@Async 注解表示该方法将异步执行。 需要注意的是,为了使 @Async 注解生效,还需要在 Spring Boot 的主类上添加 @EnableAsync 注解。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableAsync public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` 这样配置之后,定时任务将在独立的线程中异步执行,不会阻塞当前线程。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值