0
点赞
收藏
分享

微信扫一扫

@Schedule 解决定时任务推迟执行

文章目录


前言

SpringBoot 实现定时任务很简单,只需要使用**@Scheduled**注解即可,但是该注解是实现的定时任务默认是单线程的,也就意味着多个定时任务执行时就可能导致线程堵塞,延缓定时任务的执行。下面就一步一步来解决这个问题。


一、@Scheduled

1、代码

// 启用定时任务
@EnableScheduling 
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
@Component
public class Task {
    Logger logger = LoggerFactory.getLogger(Task.class);
	// 每五秒执行一次
    @Scheduled(cron = "0/5 * * * * ?")
    public void taskTestA() throws InterruptedException {
        logger.info("A:");
        TimeUnit.SECONDS.sleep(20);
        indexA++;
    }
  
    // 每十秒执行一次
    @Scheduled(cron = "0/10 * * * * ?")
    public void taskTestB() {
        logger.info("B:");
        indexB++;
    }
}

2、结果

代码

二、@Scheduled + 配置线程池

1、代码

和前面@Scheduled 相比,仅仅增加了配置线程池

// 若不设置默认为单线程,这里设置使用线程池,大小为4
spring:
  task:
    scheduling:
      pool:
        size: 4

2、结果

在这里插入图片描述

二、@Scheduled + @Async

1、代码

和前面相比,仅仅增加了配置

// 启用异步,动态创建线程
@EnableAsync  
@EnableScheduling
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
@Component
public class Task {
    private static int indexA = 0;
    private static int indexB = 0;
    Logger logger = LoggerFactory.getLogger(Task.class);
    // 异步,动态创建线程
    @Async
    @Scheduled(cron = "0/5 * * * * ?")
    public void taskTestA() throws InterruptedException {
        logger.info("A:", String.valueOf(indexA));
        TimeUnit.SECONDS.sleep(20);
        indexA++;
    }
    // 异步,动态创建线程
    @Async
    @Scheduled(cron = "0/10 * * * * ?")
    public void taskTestB() {
        logger.info("B:", String.valueOf(indexB));
        indexB++;
    }
}

2、结果

在这里插入图片描述

举报

相关推荐

spring schedule定时任务详解

0 条评论