实现步骤
1.搭建springBoot的启动类上添加注解@EnableScheduling
2.在注解类中添加线程池
3.在服务类中添加定时任务
代码实现
//启动类
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class,args);
}
}
@Configuration
public calss SwaggerConfiguration implements SchedulingConfigurer{
//设置swagger跨域,提供给service调用
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.setScheduler(taskExecutor());
}
@Bean(destroyMethod = "shutdown")
public Executor taskExecutor(){
return Executors.newScheduledThreadPool(3);
}
}
@Service
public class UserServiceImpl{
//假定有一个UserRepository类
@Autowired
private UserRepository userRepository;
//表示在每月的1日的凌晨2点调整任务
@Scheduled(cron = "0 0 2 1 * ? *")
public void deleteTiming(){
//定时清空数据库
userRepository.delete(userRepository.findAll())
}
}
个人总结
springboot通过注解的方式实现了定时器,不需要自己引入定时器和计算定时执行时间,很大程度简化了开发,cron表达式请自行查阅。