导读
由于项目需要,现在一个类中有多个定时任务,但是只能顺序执行,需要配置下让其能同时执行。
使用
原因
单个定时任务只能顺序执行,如下:
import org.springframework.scheduling.annotation.Async;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;import java.util.Calendar;import java.util.Date;@Component@Asyncpublic class Sche {/*** 每隔1s执行一次*/@Scheduled(cron = "0/1 * * * * ?")public static void pushPreNodeData() {System.out.println("测试每10s执行定时任务~");}/*** 指定时间执行一次,这里指定2020-04-10 16:37:00分执行* @throws InterruptedException*/@Scheduled(cron = "0 37 16 10 4 ?")public void pushssPreNodeData() throws InterruptedException {Calendar date = Calendar.getInstance();String year = String.valueOf(date.get(Calendar.YEAR));if ("2020".equals(year)) {while (true) {//休眠2sThread.sleep(2000);System.out.println("哈哈哈~" + new Date());}}}}
- 控制台如下:

- 此时只能单个定时任务执行,不能同时执行。如果一个没有执行完,另一个定时任务是不能同时执行的。
注意:启动类需要开启定时任务,需要添加注解 @EnableScheduling
解决办法
简单理解由于是单线程的,其不能同时执行。如果一个没有执行完,另一个定时任务是不能执行的。
如果想同事执行,可以在这里可以在启动类添加 TaskScheduler ,再次启动就可以同时执行了。
@Beanpublic TaskScheduler taskScheduler() {ThreadPoolTaskScheduler taskExecutor = new ThreadPoolTaskScheduler();taskExecutor.setPoolSize(30);return taskExecutor;}
- 控制台如下

搞定~
END
来自大佬的定时器框架demo,贼牛皮。
qyartzdemo.7z
