版权声明:本文以学习为主,欢迎转载,但必须在文章页面明显位置给出原文连接。 如果文中有不妥或者错误的地方还望高手的你指出,以免误人子弟。 https://blog.csdn.net/u014116780/article/details/84766435
在项目开发过程中,经常需要定时任务来做一些内容,比如定时进行数据统计,数据更新等。
Spring Boot默认已经实现了,我们只需要添加相应的注解就可以完成定时任务的配置。下面分两步来配置一个定时任务:
- 创建定时任务。在方法上面添加@Scheduled注解。
- 启动类添加注解,开启Spring Boot对定时任务的支持。
创建定时任务
这里需要用到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);
}
}