1.在配置类增加@EnableScheduling注解(在springboot的Application启动类或者带有@Configuration注解的类上面)开启计划任务支持。
2.在项目里写一个定时类,如:
@Component
public class SupplyReportJob {
@Scheduled(cron = "0 0/10 * * * ?")
public void doScheduledJob() {
//定时任务内容
}
}
3.如果要实现定时任务异步:增加配置类
/**
* 定时器异步
*/
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
//配置的线程的数量
taskRegistrar.setScheduler(newScheduledThreadPool(10));
}
}
4.如果想通过配置来控制所有的定时任务是否生效:可结合@ConditionalOnProperty注解来实现,增加配置类,将@EnableScheduling注解放到这个配置上,同时在application.yml文件中增加以下配置,关闭启定时任务执行则enabled配置为false,反之配置为true。@EnableScheduling
@Configuration
//代表enabled为true这个配置才生效
@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")
public class SchedulingConfig{
}
application.yml: scheduling : enabled : false