admin管理员组

文章数量:1794759

SpringBoot中使用Schedule

SpringBoot中使用Schedule

一、基本方法

有了SpringBoot貌似一切都变了非常简单,定时任务也不用整合quartz了,直接Schedule就欧了。具体咋用?非常简单。

1、引入POM依赖

Spring的Schedule包含在spring-boot-starter模块中,无需引入其他依赖。

2、开启注解支持

在启动类增加注解:@EnableScheduling

3、轻松上手使用

A、Cron表达式

// 当方法的执行时间超过任务调度频率时,调度器会在下个周期执行 @Scheduled(cron = "0/10 * * * * *") private void cronSchedule() { LOGGER.info("cronSchedule"); }

B、固定间隔

// 固定间隔,等上一次调度完成后,再开始计算间隔,再执行 @Scheduled(fixedDelay = 5000) public void fixedDelaySchedule() { LOGGER.info("fixedDelaySchedule"); }

C、固定频率

// 固定频率,如果上次调度超过了频率时间,那么在其完成后,立刻执行 @Scheduled(fixedRate = 3000) public void fixedRateSchedule() { LOGGER.info("fixedRateSchedule"); }

二、注意要点

Spring的Schecule默认是单线程执行的,如果你定义了多个任务,那么他们将会被串行执行,会严重不满足你的预期。

所以为了解决该问题,需要自定义线程池,具体如下:

/** * 自定义线程池 */ @Component public class ScheduleConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setScheduler(customScheduler()); } @Bean(destroyMethod = "shutdown") public ExecutorService customScheduler() { return Executors.newScheduledThreadPool(20); } }

本文标签: SpringBootschedule