1. 程式人生 > >Spring Boot 2.x配置定時任務

Spring Boot 2.x配置定時任務

在專案開發過程中,經常需要定時任務來做一些內容,比如定時進行資料統計,資料更新等。

Spring Boot預設已經實現了,我們只需要新增相應的註解就可以完成定時任務的配置。下面分兩步來配置一個定時任務:

  1. 建立定時任務。在方法上面新增@Scheduled註解。
  2. 啟動類添加註解,開啟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);
    }
}

執行效果