定时任务是我们项目中经常会用到的一个点,项目中使用的是xxljob,但今天这里想要总结的是关于SpringBoot使用注解方式开启定时任务;
基于注解的单线程定时任务:
1、使用注解@Scheduled、@EnableScheduling
- 启动类里面@EnableScheduling开启定时任务,自动扫描
@EnableScheduling //开启同步任务
public class BrainstormApplication {
public static void main(String[] args) {
SpringApplication.run(BrainstormApplication.class, args);
}
}
- 定时任务业务类加注解@Component被容器扫描
- 定时执行的方法加上注解@Scheduled(fixedRate=2000)定期执行一次
@Component
public class TestTask {
@Scheduled(fixedRate = 2000)
public void sum(){
System.out.println("当前时间:"+new Date());
}
}
定时任务执行结果:
2、常用注解配置:
cron 定时任务表达式@Scheduled(cron="*/1*****”)表示每秒1),crontab工具:https://tool.lu/crontab/
- fixedRate:定时多久执行一次(上一次开始执行时间点后xx秒再次执行;)
- fixedDelay:上一次执行能束时间点后xx秒再次执行
- fixedDelayString:学符串形式,可以通过配置文件指定
异步任务定时:
通过注解:@EnableAsync、@Async
@Async为异步注解,放到方法上则只作用于该方法,放在类上则作用于该类中所有的方法,表示调用该方法的线程与此方法异步执行,需要配合@EnableAsync注解使用
- 项目启动类添加注解:@EnableAsync
@EnableAsync //开启异步任务
public class BrainstormApplication {
public static void main(String[] args) {
SpringApplication.run(BrainstormApplication.class, args);
}
}
- 异步任务业务类:
@Component //添加注解@Component被容器扫描
@Async //异步任务注解
public class AsyncTask {
public void task1() throws InterruptedException{
long begin=System.currentTimeMillis();
Thread.sleep(1000L);
long end=System.currentTimeMillis();
System.out.println("任务1耗时="+(end-begin));
}
public void task2() throws InterruptedException{
long begin =System.currentTimeMillis();
Thread.sleep(2000L);
long end=System.currentTimeMillis();
System.out.println("任务2耗时="+(end-begin));
}
public void task3() throws InterruptedException{
long begin=System.currentTimeMillis();
Thread.sleep(3000L);
long end=System.currentTimeMillis();
System.out.println("任务3耗时="+(end-begin));
}
}
- Controller测试数据:
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private AsyncTask task;
@GetMapping("/test")
private Object test() {
long begin = System.currentTimeMillis();
try {
task.task1();
task.task2();
task.task3();
} catch (Exception e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("执行总耗时 : " + (end - begin));
return "test";
}
}
- 执行结果:
- 使用注解@Async的方法会被当成子线程执行,也就是在主线程执行完成后再进行执行;