当前位置: 移动技术网 > IT编程>开发语言>Java > springboot的异步任务、定时任务的简单案例

springboot的异步任务、定时任务的简单案例

2020年07月27日  | 移动技术网IT编程  | 我要评论

异步任务简单案例

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

@Service
	public class AsyncService {
	
	   public void hello(){
	       try {
	           Thread.sleep(3000);
	      } catch (InterruptedException e) {
	           e.printStackTrace();
	      }
	       System.out.println("业务进行中~~");
	  }
	}
  1. 创建controller包
  2. 在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就会自己开一个线程池进行调用
  • 改进:
  1. 给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

  1. 创建一个ScheduleService,里面编写一个hello方法,让它定时执行
@Service
publicclassScheduledService{

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

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

	@SpringBootApplication
	@EnableScheduling//开启定时任务注解功能
	@EnableAsync//开启异步注解功能
	publicclassSpringbootTaskApplication{
	
	publicstaticvoidmain(String[]args){
	SpringApplication.run(SpringbootTaskApplication.class,args);
	}
	
	}

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

本文地址:https://blog.csdn.net/L_GRAND_ORDER/article/details/107599690

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网