开启定时任务
1、启动类添加注解@EnableScheduling
2、创建任务类
关键在于@Scheduled注解,执行任务的时间
package com.example.demo.Scheduling;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class SchedulerTask {
/**
* cron表达式:每隔5秒执行一次
*/
@Scheduled(cron = "0/5 * * * * *")
public void scheduledOne(){
log.info("使用cron: {每隔5秒执行一次}");
}
/**
* cron表达式:每天16.30执行
*/
@Scheduled(cron = "0 45 10 * * *")
public void scheduledTwo() {
log.info("使用cron {每天10.30执行}");
}
/**
* 上一次 启动时间点之后每5秒执行一次
* 如果任务时长超过 fixedRate不会启动多个任务实例,只不过会在上次任务执行完后立即启动下一轮
* 除非这个类或 Job 方法用 @Async 注解了,使得任务不在 TaskScheduler 线程池中执行,而是每次创建新线程来执行。
*/
@Scheduled(fixedRate = 5000)
public void scheduledThree() {
log.info("使用fixedRate {启动时间点之后每5秒执行一次}");
}
/**
* 上一次 结束时间点之后 每5秒执行一次
*/
@Scheduled(fixedDelay = 5000)
public void scheduledFour() {
log.info("使用fixedDelay {结束时间点之后 每5秒执行一次}");
}
/**
* 第一次延迟 10秒执行,之后按照fixedRate的规则每5秒执行
*/
@Scheduled(initialDelay = 10000,fixedRate = 5000)
public void scheduledFive() {
log.info("使用initialDelay {第一次延迟 10秒执行,之后按照fixedRate的规则每6秒执行}");
}
}
以上,定时任务就结束了,所有任务的执行都是同一个线程执行。
3、开启多个线程执行定时任务
在上文的任务类加注解@Async //可加在类或方法,开启异步事件的支持
创建线程类:
package com.example.demo.Scheduling;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration //表明该类是一个配置类
@EnableAsync //开启异步事件的支持
public class AsyncConfig {
//此处成员变量使用@Value从配置中读取
@Value("${CORE_POOL_SIZE}")
private int corePoolSize;
@Value("${MAX_POOL_SIZE}")
private int maxPoolSize;
@Value("${QUEUE_CAPACITY}")
private int queueCapacity;
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.initialize();
return executor;
}
}
这样就会有多个线程去执行定时任务