跳至主要內容
SpringBoot 中定时任务的异步执行

Spring 的定时任务默认是单线程串行执行的, 那假设第一个任务比较耗时长, 直到超过任务二的设定时间之后才完成, 那么就会造成任务二不能及时完成, 进而造成其他问题

先来说说定时任务

开启对定时任务的支持, 在启动类上加上@EnableScheduling

// 启动类
@EnableScheduling
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

// 定时任务类
@Slf4j
@Service
public class ScheduledService {
    @Scheduled(fixedRate = 5000)
    public void scheduled1() {
        log.info("----{}----", Thread.currentThread().getName());
    }

    @Scheduled(cron = "0/5 * * * * *")
    public void scheduled2() {
        log.info("----{}----", Thread.currentThread().getName());
    }
}

logycoconut大约 1 分钟关于技术SpringBootAsync