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