在项目开发过程当中,常常须要定时任务来作一些内容,好比定时进行数据统计(阅读量统计),数据更新(生成天天的歌单推荐)等。java
Spring Boot默认已经实现了,咱们只须要添加相应的注解就能够完成定时任务的配置。下面分两步来配置一个定时任务:spa
建立定时任务3d
启动类添加注解code
这里须要用到Cron表达式,若是对Cron表达式不是很熟悉,能够查看cron表达式详解。orm
这是我自定义的一个定时任务:每10s中执行一次打印任务。cdn
@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对定时任务的支持。blog
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
复制代码