SpringBoot项目中,默认是串行执行的,不论启动多少任务,都是一个执行完成,再执行下一个。
如何设置并行呢? @EnableAsync 和@Async 这两个注解来实现 ,具体如下:
@EnableScheduling @EnableAsync @SpringBootApplication public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); SpringApplication app = new SpringApplication(App.class); //关闭banner app.setBannerMode(Banner.Mode.OFF); app.run(args); } }
@Service @Async public class TaskSecond { private Logger logger = LoggerFactory.getLogger(TaskSecond.class); //@Scheduled( cron = "0/2 * * * * * ") @Scheduled(fixedDelay = 20000,initialDelay = 2000) public void test(){ try { logger.info(" second start"); TimeUnit.SECONDS.sleep(10); logger.info(" second end"); } catch (InterruptedException e) { e.printStackTrace(); } } }
@Service @Async public class TaskFirst { private Logger logger = LoggerFactory.getLogger(TaskSecond.class); //@Scheduled( cron = "0/2 * * * * * ") @Scheduled(fixedDelay = 20000,initialDelay = 2000) public void test(){ try { logger.info(" first start"); TimeUnit.SECONDS.sleep(10); logger.info(" first end"); } catch (InterruptedException e) { e.printStackTrace(); } } }
原文:https://www.cnblogs.com/liuxm2017/p/10688814.html