如何实现SpringBoot异步、定时任务?

it2023-06-25  71

(一)异步任务

异步任务的需求在实际开发场景中经常遇到,Java实现异步的方式有很多,比如多线程实现异步。在SpringBoot中,实现异步任务只需要增加两个注解就可以实现。当前类添加@Async注解,启动类添加@EnableAsync

编写一个service,AsynService,让这个服务暂停3秒后再输出数据

@Service public class AsynService { @Async public void async(){ try { Thread.sleep(3000); System.out.println("执行结束"); } catch (InterruptedException e) { e.printStackTrace(); } } } 复制代码

编写controller,调用这个服务类

@RestController public class IndexController { @Autowired public AsynService asynService; @RequestMapping("/index") public String asynctask(){ asynService.async(); return "async task"; } } 复制代码

运行后在浏览器中访问http://localhost:8080/index ,会发现由于开启了异步,浏览器中会先输出async task,过了三秒后控制台才会输出执行结束。

福利 免费领取Java架构技能地图  注意了是免费送 

 

免费领取  要的+V 领取

(二)定时任务

我在之前的秒杀开源项目中已经使用过定时任务,当时的场景时,每隔1分钟去轮询数据库查询过期的商品。定时任务的应用范围很广,比如每天12点自动打包日志,每天晚上12点备份等等。 在SpringBoot实现定时任务也只需要两个注解:@Scheduled和@EnableScheduling 和前面一样,@Scheduled用在需要定时执行的任务上,@EnableScheduling用在启动类上。 首先来编写定时任务类:

@Service public class ScheduleService { @Scheduled(cron = "0/10 * * * * ? ") public void sayHello(){ System.out.println("hello"); } } 复制代码

@Scheduled注解中需要加入cron表达式,用来判断定时任务的执行时间,这里表示每10秒执行一次。

然后在启动类中加上注解@EnableScheduling。 运行项目,会发现每隔十秒会输出一条hello。

 

最新回复(0)