文章目录
- 一、基本使用
- 1、配置:@EnableScheduling
- 2、触发器:@Scheduled
- 二、拓展
- 1、修改默认的线程池
- 2、springboot配置
- 三、源码分析
- 参考资料
一、基本使用
1、配置:@EnableScheduling
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;@Configuration
// 可以省略
@EnableAsync
// 开启定时任务
@EnableScheduling
public class SchedulingConfiguration {
}
2、触发器:@Scheduled
注意:
1、要调度的方法必须有void返回,并且不能接受任何参数。
2、@Scheduled可用作可重复的注释。如果在同一个方法上发现了几个@Scheduled注解,那么它们中的每一个都将被独立处理,并为它们中的每一个触发一个单独的触发器。
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;import java.util.concurrent.TimeUnit;@Configuration
@EnableAsync
@EnableScheduling
public class SchedulingConfiguration {/*** 上一次调用结束和下一次调用开始之间的固定时间内执行* 也可以指定时间类型,默认是毫秒* @Scheduled(fixedDelay = 5, timeUnit = TimeUnit.SECONDS)*/@Scheduled(fixedDelay = 5000)public void doSomething() {System.out.println("每5秒触发一次");}/*** 以固定的时间间隔执行*/@Scheduled(fixedRate = 5, timeUnit = TimeUnit.SECONDS)public void doSomething2() {System.out.println("每5秒执行一次2");}/*** 第一次延迟1秒执行,之后每隔5秒执行一次*/@Scheduled(initialDelay = 1000, fixedRate = 5000)public void doSomething3() {// something that should run periodically}/*** 延迟1秒执行,一次性任务*/@Scheduled(initialDelay = 1000)public void doSomething4() {// something that should run only once}/*** cron表达式*/@Scheduled(cron="*/5 * * * * MON-FRI")public void doSomething5() {// something that should run on weekdays only}}
二、拓展
1、修改默认的线程池
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;@Configuration
public class TaskSchedulerConfig {// bean名称一定要是taskScheduler@Beanpublic ThreadPoolTaskScheduler taskScheduler() {ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();// 设置线程池大小scheduler.setPoolSize(5); // 设置线程名称前缀scheduler.setThreadNamePrefix("my-scheduler-"); // 设置任务拒绝策略scheduler.setRejectedExecutionHandler((r, executor) -> {System.err.println("Task " + r.toString() + " rejected from " + executor.toString());});// 初始化调度器scheduler.initialize(); return scheduler;}
}
2、springboot配置
springboot的配置:修改线程池大小等
spring.task.scheduling.pool.size=5
spring.task.scheduling.thread-name-prefix=config-scheduler-
三、源码分析
springboot默认会自动配置,创建一个ThreadPoolTaskScheduler:
但是默认的线程池的PoolSize是1
!!!这是个坑,需要注意。
参考资料
https://docs.spring.io/spring-framework/reference/integration/scheduling.html