在项目开发过程中,经常需要定时任务来做一些内容,比如定时进行数据统计(阅读量统计),数据更新(生成每天的歌单推荐)等。
Spring Boot默认已经实现了,我们只需要添加相应的注解就可以完成定时任务的配置。下面分两步来配置一个定时任务:
-
创建定时任务
-
启动类添加注解
创建定时任务
这里需要用到Cron表达式,如果对Cron表达式不是很熟悉,可以查看 cron表达式详解
。
这是我自定义的一个定时任务:每10s中执行一次打印任务。
@Component public class TimerTask { private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Scheduled(cron = "*/10 * * * * ?") // 每10s执行一次,秒-分-时-天-月-周-年 public void test() throws Exception { System.out.println(simpleDateFormat.format(new Date()) + "定时任务执行咯"); } } 复制代码
启动类添加注解
在启动类上面添加@EnableScheduling注解,开启Spring Boot对定时任务的支持。
@SpringBootApplication @EnableScheduling public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } 复制代码
原文
https://juejin.im/post/5d610080e51d45620b21c3e4
本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » Spring Boot实战(五):Spring Boot配置定时任务