本文介紹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