1.引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
2.创建定时任务配置:
package com.cc.springboot.config;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
@Configuration
@EnableScheduling //定时任务注解
public class TaskSchedulerConfig implements SchedulingConfigurer{
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
//定时任务必须构建线程池
taskRegistrar.setScheduler(schedulerThreadPool());
}
//构建线程池的方法,并设置shutdown关闭线程池
@Bean(destroyMethod="shutdown")
public Executor schedulerThreadPool() {
// 使用自定义线程池可以,推荐使用ScheduledThreadPoolExecutor
//Runtime.getRuntime().availableProcessors()当前系统允许的数量
return new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors(),
//创建一个线程工厂
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
// TODO Auto-generated method stub
Thread t = new Thread(r,"job-thread");
return t;
}
},
//最后拒绝策略
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
// TODO Auto-generated method stub
System.out.println("当前任务执行失败:"+r);
}
});
}
}
3.创建测试类:
package com.cc.springboot.task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
//声明组件【@Service 标示应用服务,@Repository 标示持久层】
@Component
public class MyJob {
//使用@Scheduled注释,initialDelay = 5000 初始化5秒启动,fixedDelay = 3000 每隔3秒启动
//@Scheduled(initialDelay = 5000,fixedDelay = 3000)
//指定细粒度的时间点去执行cron表达式,推荐使用cron表达式,比较灵活
@Scheduled(cron = "0/10 * * * * *")
public void job1() {
System.out.println("--------定时任务1执行---------");
}
}