Spring Boot 知识笔记(定时任务与异步)

一、定时任务

1、启动类里面增加注入

@SpringBootApplication    //@SpringBootApplication = @Configuration+@EnableAutoConfiguration+@ComponentScan
@Configuration
@ServletComponentScan  //扫描过滤器等servlet、filter注解
@MapperScan("net.Eleven.demo.Mapper") //扫描对应的Mapper文件

@EnableScheduling   //定时任务注解,扫描包里面所有子类中的定时任务
@EnableAsync  //开启异步任务
public class XdclassApplication extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(XdclassApplication.class);
    }
    public static void main(String[] args){

        SpringApplication.run(XdclassApplication.class,args);
    }
}

2、新建一个定时任务类

package net.Eleven.demo.task;


import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 功能描述:定时任务业务类
 *
 */

@Component
public class TestTask {
//    @Scheduled(fixedRate = 2000)  //每两秒执行一次
    @Scheduled(cron = "*/3 * * * * *") //每三秒执行一次
    public void  sendEmail(){
        System.out.println("当前时间:"+new Date());
    }
}

3、定时任务的几种配置方法

3.1、cron 定时任务表达式 @Scheduled(cron="*/1 * * * * *") 表示每秒
3.2、fixedRate: 定时多久执行一次(上一次开始执行时间点后xx秒再次执行;)
3.3、fixedDelay: 上一次执行结束时间点后xx秒再次执行
3.4、fixedDelayString: 字符串形式,可以通过配置文件指定

二、异步任务

1、启动类增加注解(@EnableAsync //开启异步任务)

2、新建一个异步任务类

package net.Eleven.demo.task;


import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
@Async  //类中所有的方法都是异步
public class AsyncTask {
    @Async //被标注的方法是异步
    public void task1() throws InterruptedException{
        long begin = System.currentTimeMillis();
        Thread.sleep(1000L);
        long end = System.currentTimeMillis();
        System.out.println("任务1耗时:"+(end-begin));
    }

    public void task2() throws InterruptedException{
        long begin = System.currentTimeMillis();
        Thread.sleep(2000L);
        long end = System.currentTimeMillis();
        System.out.println("任务2耗时:"+(end-begin));
    }

    public void task3() throws InterruptedException{
        long begin = System.currentTimeMillis();
        Thread.sleep(3000L);
        long end = System.currentTimeMillis();
        System.out.println("任务3耗时:"+(end-begin));
    }
}

3、在controller里面调用这个任务

    @Autowired
    private AsyncTask  asyncTask;
    @GetMapping("/api/async")
    public JsonData doTask() throws InterruptedException{
        long begin = System.currentTimeMillis();
        asyncTask.task1();
        asyncTask.task2();
        asyncTask.task3();
        long end = System.currentTimeMillis();
        long totalTime = end-begin;
        System.out.println("执行耗时:"+totalTime);
        return JsonData.buildSuccess(totalTime);
    }

4、执行结果

原文地址:https://www.cnblogs.com/Eleven-Liu/p/11094431.html