Spring Boot實戰(五):Spring Boot配置定時任務

在項目開發過程當中,常常須要定時任務來作一些內容,好比定時進行數據統計(閱讀量統計),數據更新(生成天天的歌單推薦)等。java

Spring Boot默認已經實現了,咱們只須要添加相應的註解就能夠完成定時任務的配置。下面分兩步來配置一個定時任務:spa

  1. 建立定時任務3d

  2. 啓動類添加註解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);
    }
}
複製代碼

執行效果

img
相關文章
相關標籤/搜索