本文主要是介绍在 SpringBoot 中使用 @EnableScheduling、@Scheduled 轻松实现定时任务,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
boot定时任务
在 main 中开启定时任务的注解 @EnableScheduling
@Slf4j
@EnableAsync
@EnableScheduling
@EnableAspectJAutoProxy
//注入 Web配置和性能监控Aop等配置
@Import(value = {ApolloConfig.class,WebConfig.class,ExecutorConfig.class,SwaggerConfig.class,//PerfMetricsConfig.class,TokenValidateConfiguration.class,com.linlong.icsa.auth.config.mybatis.DruidConfig.class,com.linlong.icsa.auth.config.mybatis.MyBatisConfig.class,com.linlong.icsa.auth.config.mybatis.MyBatisMapperScannerConfig.class,IcsaMybatisScanConfig.class,DubboConsumerConfig.class,HttpClientConfig.class,RedisLettuceSentinelConfig.class,RestTemplateConfig.class
})
//配置不使用Datasource自动配置和配置扫描Jar包中处理错误Controller
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class, RedisHealthIndicatorAutoConfiguration.class, RedisReactiveAutoConfiguration.class},scanBasePackageClasses={ErrorHandleController.class})
//mybatis扫描包配置
@MapperScan(basePackages = {"com.linlong.icsa.auth.mapper,com.linlong.icsa.auth.mobile.dao"})
//扫描Controller配置
@ComponentScan(value={"com.linlong.cloud.web.core.controller", "com.linlong.icsa.auth"})
public class App extends SpringBootServletInitializer{@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {builder.sources(App.class);return super.configure(builder);}public static void main(String[] args) {try {ApplicationContext applicationContext = SpringApplication.run(App.class, args);String[] activeProfiles = applicationContext.getEnvironment().getActiveProfiles();for(String activeProfile: activeProfiles){
// log.info("App profile: {}", activeProfile);}} catch (Exception e) {if(e.getMessage() != null){
// log.error("App.main exception: {}", e.getMessage());}}}
}
@Slf4j
@Service
public class SchedulService {@Autowiredprivate IndicateService indicateService;/*** 延迟10秒、每小时执行一次*/@Scheduled(initialDelay = 10000,fixedRate = 1000 * 60 * 5)public void batchUpdate(){log.info("scheduled now time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));indicateService.refreshIndicateRedis();}
}
这篇关于在 SpringBoot 中使用 @EnableScheduling、@Scheduled 轻松实现定时任务的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!