1、启动类中加入@EnableScheduling
2、
package guru.springframework.configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class SchedulingConfig {
// 每分钟启动
@Scheduled(cron = "0 0/1 * * * ?")
public void timerToNow() {
System.out.println("now time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
// 上一次开始执行时间点之后5秒再执行
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("现在时间:" + dateFormat.format(new Date()));
}
@Scheduled(cron = "0/20 * * * * ?") // 每20秒执行一次
public void scheduler() {
System.out.println(">>>>>>>>> SchedulingConfig.scheduler()");
}
}