SpringBoot 异步任务的简单配置及用法

本文介绍了异步任务在Spring Boot中的应用场景与好处,并通过具体示例展示了如何配置与使用异步任务,包括如何实现并发执行任务并获取执行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

异步任务的使用场景及好处

    使用场景:1.发送邮件 2.消息推送 3.执行计划任务(与消息队列)

    好处:提高效率

异步任务的简单配置

1.在SpringBootApplication启动类中增加注解 @EnableAsync开启定时任务,项目启动会自动进行扫描

2.在任务类中增加注解  @Component 及 @Async 被容器扫描 (注意:不加注解@Async为同步任务

实例

定义异步任务 其中定义完成2个方法 

import java.util.concurrent.Future;

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

@Component
public class AsyncTask {
	
	@Async
    public Future<Boolean> doTask1() throws Exception {
        long start = System.currentTimeMillis();
        Thread.sleep(1000);
        long end = System.currentTimeMillis();
        System.out.println("任务1耗时:" + (end - start) + "毫秒");
        return new AsyncResult<>(true);
    }
    
	@Async
    public Future<Boolean> doTask2() throws Exception {
        long start = System.currentTimeMillis();
        Thread.sleep(1000);
        long end = System.currentTimeMillis();
        System.out.println("任务2耗时:" + (end - start) + "毫秒");
        return new AsyncResult<>(true);
    }
    

}

测试方法

import java.util.concurrent.Future;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("tasks")
public class DoTask {
	
	@Autowired
    private AsyncTask asyncTask;
	
    @RequestMapping("taskTest")
    public String taskTest() throws Exception {
    	
    	long start = System.currentTimeMillis();
    	
    	Future<Boolean> a = asyncTask.doTask1();
    	Future<Boolean> b = asyncTask.doTask2();
    	//判断只要有任务没有完成 必须要执行这个方法
        //当所有任务执行完成之后 才可以break
    	while (!a.isDone() || !b.isDone() ) {
    		if (a.isDone() && b.isDone() ) {
    			break;
    		}
    	}
    	
    	long end = System.currentTimeMillis();
    	
    	String times = "任务全部完成,总耗时:" + (end - start) + "毫秒";
    	System.out.println(times);
    	
    	return times;
    }
}

任务结果

为什么不是1000 因为我们方法中有一个循环操作 会有一个时间的消耗 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值