SpringBoot异步任务和定时任务

 前言:本人为学习阶段,哪里有不对的地方,或者哪里可以做得更好的地方,希望各位前辈大佬指正和提出建议,感谢!


 

1、异步任务

(1)第一步在SpringBoot启动类中开启异步任务功能

@EnableAsync //开启异步任务功能
@SpringBootApplication
public class MyemailApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyemailApplication.class, args);
    }

}

(2)第二步在Service层编写一个模拟的业务

@Service
public class AsyncService {

    @Async //加上此注解标明该方法为异步任务!
    public void hello(){
        try {
            Thread.sleep(3000); //休眠3秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
     //这期间就可以做其他事情 System.out.println(
"数据正在处理..."); } }

(3)第三步在Controller层编写测试的接口

@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

    @GetMapping("/hello")
    public String hello(){
        asyncService.hello();
        return "正在进行中。。。";
    }
}

解析:如果Service层hello方法未开启异步任务的功能,此时访问“/hello”,那么需等待3秒钟才会刷新出 “正在进行中。。。” 这段字符串,而开启后,页面将立马刷新出这段字符到页面,这样给了用户更好的体验,不需要看着3秒时间的空白网页刷着。

1、定时任务

(1)和上面一样,同样是在此开启此功能(其实步骤和上述差不多)

@EnableScheduling //开启定时功能的注解
@SpringBootApplication
public class MyemailApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyemailApplication.class, args);
    }
}

(2)这里需要注意cron表达式,

@Service
public class ScheduledService {

    //在一个特定的时间执行 参数为cron表达式
    @Scheduled(cron = "10 * * * * ?") //秒 分 时 日 月 周几  此意为 无论在哪一时刻,秒钟跑到10s这个位置,就会执行此方法
    public void hello(){
        System.out.println("你被执行了!");
    }
}

cron表达式在线转换地址:https://cron.qqe2.com/

今天的总结到此结束啦,如果对您有帮助,可以为我点赞噢!


 

2020-10-14

 

posted @ 2020-10-14 00:14  头发茂盛  阅读(199)  评论(0)    收藏  举报