springboot使用异步+定时任务 解决定时任务阻塞的问题

    科技2022-07-21  101

    import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; /** * 定时任务: * 1.@EnableScheduling 开启定时任务 * 2.@Scheduled 开启一个定时任务 * 3.自动配置类:TaskSchedulingAutoConfiguration * <p> * 异步任务: * 1.@EnableAsync 开启异步任务功能 * 2.@Async 给异步执行的方法标上该注解 * 3.自动配置类:TaskExecutionAutoConfiguration */ @EnableScheduling @EnableAsync @Slf4j @Component public class HelloSchedule { /** * 1.在spring中6位组成 不能是7位 * 2.在周几的位置 1-7 代表周一到周日 * 3.定时任务不能阻塞 默认是阻塞的 * 1)可以让业务运行以异步的方式 自己提交到线程池 --> CompletableFuture.runAsync() * 2) 支持定时任务线程池 设置TaskSchedulingProperties * spring.task.scheduling.pool.size=5 有些版本不太管用。。 * 3)定时任务异步执行 * 异步任务: * * 解决:使用异步+定时任务解决定时任务阻塞的问题 */ @Scheduled(cron = "* * * ? * 7") @Async public void hello() { log.info("hello...."); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } } }
    Processed: 0.011, SQL: 8