1. 程式人生 > >springboot 專案框架搭建(一):新增定時任務

springboot 專案框架搭建(一):新增定時任務

ps: 在我們的專案開發過程中,經常需要定時任務來幫助我們來做一些內容,springboot預設已經幫我們實行了,只需要新增相應的註解就可以實現

一.構建專案,如圖所示:

    

 建立一個用於執行定時任務的介面,以及一個介面的實現類。

二.添加註解

      在啟動類新增定時註解 @EnableScheduling

     

在實現類新增定時任務,哪個方法需要執行定時任務,則新增到哪個方法上。

import com.example.smalserver.http.service.server.TimingService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * @Author: caohuijie
 * @Date: 建立日期 2018/11/7
 * @Modified By:
 * @Description: 定時任務類
 */
@Component
@Service
public class TimingServiceImpl implements TimingService {

    private int count=0;

    @Scheduled(cron="*/6 * * * * ?")
    @Override
    public void timingTask() {
        System.out.println("this is scheduler task runing  "+(count++));
    }
}

 或者:

import com.example.smalserver.http.service.server.TimingService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * @Author: caohuijie
 * @Date: 建立日期 2018/11/7
 * @Modified By:
 * @Description: 定時任務類
 */
@Service
public class TimingServiceImpl implements TimingService {

    private int count=0;

    @Scheduled(cron="*/6 * * * * ?")
    @Override
    public void timingTask() {
        System.out.println("this is scheduler task runing  "+(count++));
    }
}

corn表示式:

"0 0 * * * *" 表示每小時0分0秒執行一次

" */10 * * * * *" 表示每10秒執行一次

"0 0 8-10 * * *" 表示每天8,9,10點執行

"0 0/30 8-10 * * *" 表示每天8點到10點,每半小時執行

"0 0 9-17 * * MON-FRI" 表示每週一至週五,9點到17點的0分0秒執行

"0 0 0 25 12 ?" 表示每年聖誕節(12月25日)0時0分0秒執行