摘要:項目中經常會需要做一些定時的跑的事情,比如每間隔多久做個統計,發個郵件,清理個數據。這時候就要用到定時任務,SpringBoot中,創建定時任務非常簡單,具體步驟如下:
1.開啓定時任務
在程序的入口類中添加@EnableScheduling註解
- package com.alibaba;
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.cache.annotation.EnableCaching;
- import org.springframework.scheduling.annotation.EnableAsync;
- import org.springframework.scheduling.annotation.EnableScheduling;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RestController;
- /**
- * the entrance of the application
- */
- @EnableAsync
- @RestController
- @SpringBootApplication
- @EnableCaching
- @EnableScheduling
- //掃描dao
- @MapperScan("com.alibaba.dao")
- public class TmallApplication {
- public static void main(String[] args) {
- SpringApplication.run(TmallApplication.class, args);
- }
- @RequestMapping(value = "hello",method = RequestMethod.GET)
- public String getHello(){
- return "hello world";
- }
- }
單獨創建一個類,用來存放定時任務,然後在每個定時任務方法上,用註解標明定時任務的執行週期。我這裏以每間隔10秒打印一下當前系統時間爲例。
- package com.alibaba.task;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.scheduling.annotation.Scheduled;
- import org.springframework.stereotype.Component;
- /**
- * Created by lightClouds917
- * Date 2018/2/6
- * Description:定時任務
- */
- @Component
- public class ScheduledTask {
- private final Logger logger = LoggerFactory.getLogger(getClass());
- /**
- * 每間隔10秒輸出時間
- */
- @Scheduled(fixedRate = 10000)
- public void logTime(){
- logger.info("定時任務,現在時間:"+System.currentTimeMillis());
- }
- }
@Scheduled(fixedRate = 5000) :上一次開始執行時間點之後5秒再執行
@Scheduled(fixedDelay = 5000) :上一次執行完畢時間點之後5秒再執行
@Scheduled(initialDelay=1000, fixedRate=5000) :第一次延遲1秒後執行,之後按fixedRate的規則每5秒執行一次
@Scheduled(cron="*/5 * * * * *") :通過cron表達式定義規則
注意,這裏的時間,單位是毫秒,1秒=1000毫秒
4.運行項目