这篇文章主要介绍“springboot定时任务和异步任务怎么实现”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“springboot定时任务和异步任务怎么实现”文章能帮助大家解决问题。
在我们开发项目时,常常会用到异步处理任务,比如我们在网站上发送邮件,后台会去发送邮件,此时会造成前台响应不动,直到邮件发送完毕,响应才会成功,所以我们一般会采用多线程的方式去处理这些任务。
新建一个service
包
创建AsyncService
类
@Service
public class AsyncService {
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("业务进行中~~");
}
}
创建controller
包
在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////
关于“springboot定时任务和异步任务怎么实现”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。