title:SpringBoot整合Async,Scheduled
time: 2019年8月25日11:23:53
tags:Async
SpringBoot整合Async
-
在要开启异步的方法前加入@Async
@Service public class AsyncService { @Async public void testAsync() throws InterruptedException { Thread.sleep(5000); //默认是先执行,休眠操作,再执行下面的打印操作 //开启异步后,可以在休眠时,阻塞时,进行下个操作的进行。 System.out.println("插入数据中、、、、"); } }
-
并在application类前加入@EnableAsync
@SpringBootApplication @EnableAsync public class AsyncApplication { public static void main(String[] args) { SpringApplication.run(AsyncApplication.class, args); } }
-
测试
@RestController public class HelloController { @Autowired AsyncService asyncService; @RequestMapping("/hello") public String hello() throws InterruptedException { asyncService.testAsync(); return "success"; } }
SpringBoot整合Scheduled
-
在你要加入定时任务方法的前面添加@Scheduled注解
@Service public class ScheduledService { /* corn()参数 second ,minute, hour, day of month, month ,day of week. * "0 * * * * MON-FRI" 表示周一到周五每月每天每小时每分钟的0秒执行 * 中间用空格分开 * */ //表示周一到周六每一分钟的前4秒执行 @Scheduled(cron = "0-4 * * * * MON-SAT") public String hello() { String x = "一分钟过去了,你这一分钟做了些什么,学到了什么东西"; System.out.println(x); return x; } }
-
并在application类前加入@EnableScheduling
@SpringBootApplication @EnableAsync @EnableScheduling public class AsyncApplication { public static void main(String[] args) { SpringApplication.run(AsyncApplication.class, args); } }
-
测试
@RestController public class AsyncController { @Autowired AsyncService asyncService; @RequestMapping("/hello") public String hello() throws InterruptedException { asyncService.testAsync(); return "success"; } }