一,导入所需要的依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.0.0</version>
</dependency>二、创建定时任务
2.1创建定时任务
@Configuration
@EnableAsync
@Async
public class TestOne {
@Scheduled(cron="0/2 * * * * ?")
public void funOne(){
System.out.println("定时任务1");
System.out.println(Thread.currentThread().getName()+" 11111111111");
}
}
定时任务执行默认是单线程模式,会创建一个本地线程池,线程池大小为1。当项目中有多个定时任务时,任务之间会相互等待,同步执行
@EnableAsync为开启异步任务,如果不加上这个,定时任务将使用同一个线程,有可能会导致阻塞,不同版本默认的线程池大小不一致,2.2.0线程池大小为8
@Configuration
@EnableAsync
@Async
public class TestTwo {
@Scheduled(cron="0/2 * * * * ?")
public void funOne(){
System.out.println("定时任务2");
System.out.println(Thread.currentThread().getName()+" 2222222222");
}
}2.2 @Scheduled注解的使用
2.2.1 cron 表达式
Cron表达式由6或7个空格分隔的时间元素组成,按照顺序依次如下表所示:
字段 | 允许值 | 允许的特殊字符 |
秒 | 0~59 | -*/ |
分钟 | 0~59 | -*/ |
小时 | 0~23 | -*/ |
日期 | 0~31 | ,-*?/LWC |
月份 | 0~11 | -*/ |
星期 | 1~7,1为SUN-依次为SUN,MON,TUE,WED,THU,FRI,SAT | ,-*?/LC# |
年(可选) | 留空,1970-2099 | -*/ |
@Scheduled(cron="0/2 * * * * ?")为每2秒钟执行一次
2.2.2 fixedDelay
@Scheduled(fixedDelay = 5000)
延迟执行。任务在上个任务完成后达到设置的延时时间就执行。
此处,任务会在上个任务完成后经过5s再执行。
2.2.3 fixedRate
@Scheduled(fixedRate = 5000)
定时执行。任务间隔规定时间即执行。
此处,任务每隔五秒便会执行一次。
2.3自定义线程池
如果不想使用自带线程池,可以自定义线程池
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean(name="myExecutor")
public ThreadPoolTaskExecutor mqInvokeAysncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 线程池中的线程名前缀
executor.setThreadNamePrefix("log-message-");
// 设置线程池关闭的时候需要等待所有任务都完成 才能销毁其他的Bean
executor.setWaitForTasksToCompleteOnShutdown(true);
// 设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住
executor.setAwaitTerminationSeconds(120);
// 核心线程数
executor.setCorePoolSize(4);
// 最大线程数
executor.setMaxPoolSize(16);
// 任务阻塞队列的大小
executor.setQueueCapacity(20000);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}然后在需要使用到该线程池的类上,注解@Async后面加上线程池的名称,便可使用该线程池
@Configuration
@EnableAsync
@Async("myExecutor")
public class TestTwo {
@Scheduled(cron="0/2 * * * * ?")
public void funOne(){
System.out.println("定时任务2");
System.out.println(Thread.currentThread().getName()+" 2222222222");
}
}
762

被折叠的 条评论
为什么被折叠?



