1、现在application类中增加注解@EnableScheduling开启定时器
import org.springframework.boot.SpringApplication;2、新建一个Scheduler类,设定时间或频率就好了
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class Scheduler{
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
//每隔2秒执行一次
@Scheduled(fixedRate = 2000)
public void testTasks() {
System.out.println("定时任务执行时间:" + dateFormat.format(new Date()));
}
// //每天3:05执行
// @Scheduled(cron = "0 05 03 ? * *")
// public void testTasks() {
// System.out.println("定时任务执行时间:" + dateFormat.format(new Date()));
// }
}

网友回复