SpringBoot + Scheduling(定时任务)
- 完成简单的定时任务,SpringBoot框架实现
- @Scheduled注解式(cron语言,fixedDelay或者间隔时间)
- 基于SchedulingConfigurer接口实现
一、@Scheduled注解式
@Component被spring管理;@EnableScheduling开启定时任务;@Configuration开启配置;@Scheduled方法执行时间;@async如果配置了线程池 , 可以开启异步执行,但是方法需要公有化 ‘public’。
- application.yml 配置变量
job:
task2: 0/15 * * * * ?
- 方法配置
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@EnableScheduling
@Configuration
public class QutrzConfig {
/**
* 如果配置了线程池 , 可以开启异步执行
* 但是方法需要公有化 ‘public’
*/
// @Async
@Scheduled (cron = "0/5 * * * * ?")
private void task (){
System.out.println("爱我中华!");
}
@Scheduled (cron = "${job.task2}")
private void task2 (){
System.out.println("中华崛起!");
}
}
- 执行结果
一、SchedulingConfigurer接口式
@Component被spring管理;@EnableScheduling开启定时任务;@Configuration开启配置。
- 方法配置
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
@Component
@EnableScheduling
@Configuration
public class QutrzConfig2 implements SchedulingConfigurer {
private String getCron (){
//可以通过不同的方式获取执行时间
return "0/10 * * * * ?";
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(
//1.添加任务内容(Runnable)
() -> {
System.out.println("奋青!");
},
//2.设置执行周期(Trigger)
triggerContext -> {
String cron = this.getCron();
return new CronTrigger(cron).nextExecutionTime(triggerContext);
}
);
}
}
- 执行结果
chenyb 随笔记录,方便学习
2020-09-21