在启动类加上@EnableScheduling注解
package com.dfyang;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
//开启定时任务
@EnableScheduling
public class SchedulerApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulerApplication.class, args);
}
}
@Scheduled注解的参数详解
- cron:使用cron表达式
- zone:时区,默认即可
- fixedDelay:按时间间隔执行
- fixedDelayString:按时间间隔执行,只不过输入的字符串
- fixedRate:按多少秒执行
- fixedRateString:按多少秒执行,只不过输入的字符串
- initialDelay:延迟多少秒执行第一次定时任务
- initialDelayString:延迟多少秒执行第一次定时任务,只不过输入的字符串
由于并不难,所以只举了两个例子。
fixedRate:按多少秒执行
package com.dfyang.scheduler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class SchedulerTask {
private static final SimpleDateFormat sdf =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 1s钟执行一次
* @return
*/
@Scheduled(fixedRate = 1000)
public void printCurrentTime() {
System.out.println(sdf.format(new Date()));
}
}
Cron:使用cron表达式
package com.dfyang.scheduler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class SchedulerTask {
private static final SimpleDateFormat sdf =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 每分钟的0s、10s、20s、30s、40s、50s执行一次
* @return
*/
@Scheduled(cron = "0,10,20,30,40,50 * * * * ?")
public void printCurrentTime() {
System.out.println(sdf.format(new Date()));
}
}