前言
在实际中,我们往往需要一些定时任务,比如在每日的晚些时候有些跑批的账务操作,月末报表生成等。这就需要用到定时任务
1、准备一个线程池
准备一个线程池并交给spring托管
@Configuration
public class ScheduleConfig {
@Bean("taskExecutor")
public Executor taskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程数
executor.setCorePoolSize(4);
//最大核心线程数
executor.setMaxPoolSize(10);
//设置队列中等待被调度处理的任务数量
executor.setQueueCapacity(8);
return executor;
}
}
2、将需要调度的逻辑交由线程池
/**
* autor:liman
* createtime:2019/12/14
* comment: 通用的定时任务
*/
@Component
@Slf4j
public class CommonScheduler {
@Autowired
private AuthTokenMapper authTokenMapper;
@Scheduled(cron = "0/60 * * * * ? ")//10S执行一次的表达式
@Async("taskExecutor")
public void deleteAnyInvalidateToken(){
try{
log.info("--删除无效token的批次开始执行--");
authTokenMapper.deleteUnactiveToken();
}catch (Exception e){
log.error("--删除无效的token批次执行异常");
}
log.info("--删除无效token的批次执行结束--");
}
}
这里有两个注解,一个是@Scheduled和@Async注解,前者可以通过指定cron表达式完成定时的设置,后置标示这个方法为异步方法,指定线程池的名称,这个方法会交给上述的线程池调度。
3、cron表达式
cron表达式是可以通过表达式灵活的配置运行的方式,cron有6~7个空格分隔的时间元素,按照顺序依次是“秒,分,时,天,月,星期,年”,其中年是一个不可配置的元素。具体可以参看这篇博客——cron表达式总结
上述中我们指定的是没60秒执行一次。
4、告知启动类
//在springboot启动类中加上@EnableAsync和@EnableScheduling两个注解
//前者是让springboot可以异步执行带有@Async注解的方法,后者是让springboot可以执行@Scheduling注解的方法
@SpringBootApplication
@ImportResource(locations = {"classpath:spring/spring-jdbc.xml"})
@MapperScan(basePackages = "com.learn.springauthmodel.mapper")
@EnableAsync
@EnableScheduling
public class AuthServerStarterApplication {
public static void main(String[] args) {
SpringApplication.run(AuthServerStarterApplication.class, args);
}
}
总结
不是总结的总结,done!