springboot成神之——Scheduler定時任務


本文介紹spring的Scheduler定時任務

目錄結構

config

// @EnableScheduling 開啟后台任務
package com.springlearn.learn.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@EnableScheduling
public class SchedulerConfig {
}

scheduler

// 獲取當前時間

package com.springlearn.learn.scheduler;

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

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class GetCurrentTimeSchedule {
    private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss sss");

    @Scheduled(initialDelay=3*1000, fixedDelay=1*1000)
    public void GetCurrentTime() {
        Date now = new Date();
        System.out.println("Now is:" + df.format(now));
    }
}

@Scheduled配置參數

cron
    second, minute, hour, day of month, month, day(s) of week
    @Scheduled(cron="0 * * * * *" ) 每分鍾執行一次
    @Scheduled(cron="*/10 * * * * *") 每10秒執行一次
    @Scheduled(cron="*0 0 8-10 * * *") 8點,9點,10點各執行一次
    @Scheduled(cron="0 0/30 8-10 * * *") 8點,8點半,9點,9點半,10點,10點半各執行一次
    @Scheduled(cron="0 0 9-17 * * MON-FRI") 周一到周五的每天的9點到17點各執行一次
    @Scheduled(cron="0 0 0 1 1 ?") 元旦節午夜執行一次
zone    
    時區
    @Scheduled(cron="0 * * * * *", zone="Asia/Shanghai")
fixedDelay 
    當上一個任務完成,才會執行下一個
fixedDelayString
fixedRate
    不管上一個任務完沒完成,時間一到,都會執行下一個
fixedRateString
initialDelay
initialDelayString


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM