springboot 定时任务,异步任务的案例分享

猿友 2020-07-28 15:47:56 浏览数 (3246)
反馈

整理这篇文章是为了给大家分享两个springboot的异步任务、定时任务的简单案例,让大家有个参考对象。

异步任务简单案例

在我们开发项目时,常常会用到异步处理任务,比如我们在网站上发送邮件,后台会去发送邮件,此时会造成前台响应不动,直到邮件发送完毕,响应才会成功,所以我们一般会采用多线程的方式去处理这些任务。

  1. 新建一个service

  1. 创建AsyncService

@Service
    public class AsyncService {

    
       public void hello(){
           try {
               Thread.sleep(3000);
          } catch (InterruptedException e) {
               e.printStackTrace();
          }
           System.out.println("业务进行中~~");
      }
    }

  1. 创建controller

  1. controller包下创建一个AsyncController

@RestController
    public class AsyncController {

    
       @Autowired
       AsyncService asyncService;

    
       @GetMapping("/hello")
       public String hello(){//调用方法后会延迟3秒在页面显示Success
           asyncService.hello();
           return "success";
      }

    
    }

此时访问Localhost:8080/hello的情况是:延迟3秒后,在页面输出Success,在后台会输出业务进行中~~

新问题:如果想页面直接输出信息“Success”,而让这个hello方法直接在后台用多线程操作,就需要加上@Async注解,这样spring boot就会自己开一个线程池进行调用

改进:给AsyncService加上注解

@Async//告诉Spring这是一个异步方法
    public void hello(){
       try {
           Thread.sleep(3000);
      } catch (InterruptedException e) {
           e.printStackTrace();
      }
       System.out.println("业务进行中~~");
    }

但是要让这个注解起作用,还需要在入口文件中开启异步注解功能

@EnableAsync //开启异步注解功能
@SpringBootApplication
    public class SpringbootTaskApplication {
           public static void main(String[] args) {
               SpringApplication.run(SpringbootTaskApplication.class, args);
          }
    }

此时再次测试,发现页面直接输出了Success,但是后台仍然是3秒后输出业务进行中

定时任务简单案例

工作中常常要设置一些定时任务,比如每天在某个时间分析一遍日志

所以Spring提供了异步执行任务调度的方式,提供了两个接口。

TaskExecutor接口

TaskScheduler接口

两个注解:

• @EnableScheduling

• @Scheduled

创建一个ScheduleService,里面编写一个hello方法,让它定时执行

@Service
publicclassScheduledService{


    //秒分时日月周几
    @Scheduled(cron="0 * * * * ?")
    //这里需要学习一些cron表达式的语法,明白时间如何设置,这里的意思是每当时间到0秒时就执行一次
    publicvoidhello(){
        System.out.println("hello/////");
    }
}

要使用定时功能,还需要在入口文件中加上@EnableScheduling,表明开启定时任务功能

@SpringBootApplication
    @EnableScheduling//开启定时任务注解功能
    @EnableAsync//开启异步注解功能
    publicclassSpringbootTaskApplication{

    
    publicstaticvoidmain(String[]args){
    SpringApplication.run(SpringbootTaskApplication.class,args);
    }

    
    }

此时测试运行,发现每当时间为0秒时就会在后台打印出 hello////

任务输出结果

以上就是分享的两个简单案例,对SpringBootjava有学习兴趣的同学,可以看一下教程

Java教程:https://www.w3cschool.cn/java/

Java微课:https://www.w3cschool.cn/minicourse/play/javaminicourse

SpringBoot教程:https://www.w3cschool.cn/seansblog/

SpringBoot从入门到精通微课:https://www.w3cschool.cn/minicourse/play/springboot_my

0 人点赞