Spring Boot实战(五):Spring Boot配置定时任务

780 阅读1分钟

在项目开发过程中,经常需要定时任务来做一些内容,比如定时进行数据统计(阅读量统计),数据更新(生成每天的歌单推荐)等。

Spring Boot默认已经实现了,我们只需要添加相应的注解就可以完成定时任务的配置。下面分两步来配置一个定时任务:

  1. 创建定时任务

  2. 启动类添加注解

创建定时任务

这里需要用到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);
    }
}

执行效果

img