SpringBoot如何实现异步任务、定时任务呢?
下文笔者讲述SpringBoot实现异步任务、定时任务的方法分享,如下所示
异步任务
异步任务常用于发送邮件或处理数据时 避免阻塞线程 影响用户体验 此时我们需采用异步任务
异步任务的实现思路
spring中我们只需使用注解@Async 1.该注解标注在方法上 spring则认为这是一个异步方法 2.主启动类上使用@EnableAsync开启异步注解功能例:异步任务的示例
@RestController public class AsynController { @Autowired AsyncService asyncService; @GetMapping("/hello") public String hello(){ asyncService.hello(); return "success"; } } @Service public class AsyncService { public void hello(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("数据处理中..."); } } //启动项目 //访问localhost:8080/hello //页面在3秒之后才返回success //严重影响用户体验 //需要使用异步任务 @Service public class AsyncService { @Async public void hello(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("数据处理中..."); } } @EnableAsync @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
定时任务
定时任务: 企业级开发中最常见的功能之一 如: 定时统计订单数 数据库备份 定时发送短信和邮件 定时统计博客访客等 简单的定时任务 可直接通过Spring中的@Scheduled注解来实现 复杂的定时任务则可通过集成Quart来实现开启定时任务的示例
项目启动类上 添加@EnableScheduling注解 即可开启定时任务例:
@EnableScheduling @EnableAsync @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } 配置定时任务 @Component public class MySchedule { //当前任务执行结束1秒后开启下一次任务 @Scheduled(fixedDelay = 1000) public void fixedDelay(){ System.out.println("fixedDelay:" + new Date()); } //当前任务开始2秒后,开启下一次定时任务 @Scheduled(fixedRate = 2000) public void fixedRate(){ System.out.println("fixedRate:" + new Date()); } //initialDelay表示首次执行的延迟时间 @Scheduled(initialDelay = 1000, fixedRate = 2000) public void initialDelay(){ System.out.println("initialDelay:" + new Date()); } //cron表达式:表示该定时任务每分钟执行1次 @Scheduled(cron = "0 * * * * ?") public void cron(){ System.out.println("cron:" + new Date()); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。