先看普通状态下的打印结果。使用定时任务前提 是要 配置好 @EnableScheduling。链接
@Componentpublic class ScheduleTask {@Scheduled(cron = "0/5 * * * * *")public void startAAATasks(){System.out.println("任务111,开始时间:" + dateFormat.format(new Date()));try {Thread.sleep(1000);}catch (Exception e){e.printStackTrace();}System.out.println("任务111,结束时间:" + dateFormat.format(new Date()));}@Scheduled(cron = "0/5 * * * * *")public void startBBBTasks(){System.out.println("任务222,开始时间:" + dateFormat.format(new Date()));try {Thread.sleep(1000);}catch (Exception e){e.printStackTrace();}System.out.println("任务222,结束时间:" + dateFormat.format(new Date()));}
这里有两个任务,这个每5秒执行一次的任务,每个任务 我中间,睡眠1秒。发现打印结果是,两个任务运行时间,是串行下来了,其中一个执行结束,另一个才开始。

定时任务 并行的方法一
public class PrisonManageApplication {/*** 启动程序.** @param args*/public static void main(String[] args) {SpringApplication.run(PrisonManageApplication.class, args);System.out.println("启动成功~~~~~~~~~~");}// 启动类加上这串代码@Beanpublic TaskScheduler taskScheduler() {ThreadPoolTaskScheduler taskExecutor = new ThreadPoolTaskScheduler( ) ;taskExecutor. setPoolSize(50) ;return taskExecutor ;}}
定时任务 并行的方法二
给类添加注解@EnableAsync,并给方法添加注解@Async。
@Component@EnableAsyncpublic class ScheduleTask {@Async@Scheduled(cron = "0/5 * * * * *")public void startAAATasks(){System.out.println("任务111,开始时间:" + dateFormat.format(new Date()));try {Thread.sleep(1000);}catch (Exception e){e.printStackTrace();}System.out.println("任务111,结束时间:" + dateFormat.format(new Date()));}@Async@Scheduled(cron = "0/5 * * * * *")public void startBBBTasks(){System.out.println("任务222,开始时间:" + dateFormat.format(new Date()));try {Thread.sleep(1000);}catch (Exception e){e.printStackTrace();}System.out.println("任务222,结束时间:" + dateFormat.format(new Date()));}}
两个方法结果都一样,可以看到两个任务的启动时间是同时的
