springboot自己集成的定时任务
- 在启动类上添加 @EnableScheduling // springboot 自己的定时任务
- 写一个定时类
@Component
public class TestJob {
@Scheduled(cron = "0/2 * * * * *") // 2秒执行一次
public void job(){
System.out.println("springboot - EnableScheduling ");
}
}
springboot 集成quartz定时器
- pom.xml 添加quartz依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
- application.properties配置文件(线程池的基本大小、数据库最大连接池、线程并发数)
corePoolSize=10
maxPoolSize=200
queueCapacity=10
- 添加定时类
@DisallowConcurrentExecution
public class TestQuartz extends QuartzJobBean{
/**
* 执行定时任务
* @param context
* @throws JobExecutionException
*/
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
System.out.println("quartz定时任务");
}
}
- springboot 可以配置一个通过线程池异步优化,可以启用多线程的方式来执行了,更加高效
@Configuration
@EnableAsync
public class AsyncConfig {
@Value("${corePoolSize}")
private int corePoolSize;
@Value("${maxPoolSize}")
private int maxPoolSize;
@Value("${queueCapacity}")
private int queueCapacity;
@Bean
public Executor taskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.initialize();
return executor;
}
}
- 结合quartz框架做一些配置
@Configuration
public class TestQuartzConfig {
@Bean
public JobDetail testQuartzDetail(){
return JobBuilder.newJob(TestQuartz.class)
.withIdentity("zxf").storeDurably()
.requestRecovery(true).build();
}
@Bean
public Trigger testQuartzTrigger(){
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("name","zxf");
SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder
.simpleSchedule()
.withIntervalInSeconds(2) //设置时间周期单位秒
.repeatForever();
return TriggerBuilder.newTrigger().forJob(testQuartzDetail())
.withIdentity("zxf")
.withSchedule(simpleScheduleBuilder)
.usingJobData(jobDataMap)
.build();
}
}
启动后效果如图:
动态配置时间设置
- @PropertySource(“classpath:application-test.properties”)在类上添加你对应的配置文件地址
- @Scheduled(cron={aaa.bbb}) 配置文件里设置定时时间 设置你配置的指定名称