1. 程式人生 > >SpringBoot定時任務Schedule (七)

SpringBoot定時任務Schedule (七)

在日常專案執行中,我們總會有需求在某一時間段週期性的執行某個動作。比如每天在某個時間段匯出報表,或者每隔多久統計一次現在線上的使用者量。在springboot中可以有很多方案去幫我們完成定時器的工作,有Java自帶的java.util.Timer類,也有強大的排程器Quartz,還有SpringBoot自帶的Scheduled,今天主要說說Scheduled。

定時器比較

框架名稱 Cron表示式 固定間隔執行 固定頻率執行 任務持久化 難易度

在實際應用中,如果沒有分散式場景(quartz 支援分散式, schedule 不支援(需要自己實現,用分散式鎖),schedule跟spring結合的更好,還是很適用的。

建立schedule工程

使用IntelliJ IDEA建立helloschedule

SpringBoot(九)定時任務Schedule

SpringBoot(九)定時任務Schedule

SpringBoot(九)定時任務Schedule

SpringBoot(九)定時任務Schedule

SpringBoot(九)定時任務Schedule

點選finish完成專案的建立。

SpringBoot(九)定時任務Schedule

為了方便演示,使用@Slf4j輸出日誌,新增lombok引用,@Slf4j不清楚的可以看看SpringBoot(八)配置logback日誌

新增export類。

package com.task.log;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by toutou on 2018/10/20.
 */
@Component
@Slf4j
public class export {
    @Scheduled(cron = "0 0/1 * * * ?")
    public void minuteExport(){
        log.debug("每分鐘執行一次的任務:" + getDate());
    }

    @Scheduled(fixedRate = 5000)
    public void fiveSecondExport(){
        log.debug("每5秒執行一次:" + getDate());
    }

    @Scheduled(cron = "0/2 * * * * ?")
    public void twoSecondExport(){
        log.debug("每2秒執行一次:" + getDate());
    }

    @Scheduled(cron = "0 55 14 ? * *")
    public void regularTimeExport(){
        log.debug("每天上午14點55分執行:" + getDate());
    }

    private String getDate(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }
}

啟動類中新增@EnableScheduling註解,然後執行。

SpringBoot(九)定時任務Schedule

檢視IntelliJ IDEA控制檯日誌和物理檔案日誌

SpringBoot(九)定時任務Schedule

SpringBoot(九)定時任務Schedule

如上圖,簡單的定時任務輸出日誌搭建完成。