1.定时任务schedule
-
springboot使用注解方式开启定时任务
- 启动类加上@EnableScheduling开启定时任务自动扫描
- 定时任务业务类加注解@Component被容器扫描
- 定时执行的方法加上注解@Scheduled(fixedRate = 10000)
-
定时规则
- @Scheduled(cron = “* * * * * *”):定时任务表达式,分别表示秒分时日月周
- @Scheduled(fixedRate = 1000):定时1秒执行一次
- @Scheduled(fixedDelay = 1000):上一次代码执行结束后1秒再执行;假如代码需要执行1秒,也就是说每2秒执行一次
-
代码示例
package com.gen.schedule; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.time.LocalDateTime; @Component public class CustomSchedule { @Scheduled(cron = "* * * * * *") public void testSchedule() { System.out.println(LocalDateTime.now()); } }
2.异步任务
-
springboot使用注解方式开启异步任务
- 启动类加上@EnableAsync注解开启功能自动扫描
- 定义异步任务类并使用@Component被容器扫描,异步方法加上@Async
- 如果需要异步类返回结果,增加Future返回结果AsyncResult,调用处拿返回结果时,判断是否完成isDone()
-
代码示例
-
异步类
package com.gen.async; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Component; import java.util.concurrent.Future; @Component public class CustomAsync { @Async public void test1() { try { Thread.sleep(1000L); System.out.println("异步任务test1"); } catch (InterruptedException e) { e.printStackTrace(); } } @Async public Future<String> test2() { try { Thread.sleep(2000L); System.out.println("异步任务test2"); } catch (InterruptedException e) { e.printStackTrace(); } return new AsyncResult("任务返回值"); } }
-
controller调用
@Autowired private CustomAsync customAsync; @GetMapping("test") public void test() { this.customAsync.test1(); Future<String> stringFuture = this.customAsync.test2(); while (true) { if (stringFuture.isDone()) { try { System.out.println(stringFuture.get()); } catch (Exception e) { e.printStackTrace(); } finally { break; } } } }
-