SpringBoot定时任务与异步任务
1.定时任务
1-1.SpringBoot使用注解方式开启定时任务
-
启动类添加@EnableScheduling开启定时任务,自动扫描
-
编写定时任务业务类,@Component被容器扫描
-
定时执行的方法加上注解@Scheduled(fixedRate = 2000),每2秒执行一次
package com.gen.schedule; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.time.LocalDateTime; /** * 定时任务业务类 */ @Component public class ScheduleTask { // 每2秒执行一次 @Scheduled(fixedRate = 2000) public void testSchedule() { System.out.println(LocalDateTime.now() + "----------"); } }
1-2.多种定时任务配置
- cron定时任务表达式@Scheduled(cron = "*/1 * * * * *")表示每秒执行
- *分别对应:秒 分 时 日 月 周
- fixedRate:定时多久执行一次(执行开始)
- fixedDelay:定时任务执行完毕后多久执行一次(执行完毕)
2.异步任务
2-1.使用说明
- 启动类添加@EnableAsync注解开启功能,自动扫描
- 编写异步任务类并使用@Component被容器扫描,异步方法加上@Async
2-2.异步任务返回值
-
要把异步任务封装到类里面,不能直接写到Controller
-
使用Future作为返回值,返回结果AsyncResult()
-
如果需要拿到结果,需要判断全部的isDone()方法,使用get()方法接收参数
package com.gen.task; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Component; import java.util.concurrent.Future; @Component @Async public class AsyncTask { // 没有返回值 public void task1() { System.out.println("task1 ----------"); } // 有返回值 public Future<String> task2() { System.out.println("task2 ----------"); return new AsyncResult("这是返回值"); } }
浙公网安备 33010602011771号