1.启动类上添加注解
@EnableScheduling //启用定时器功能
@SpringBootApplication() @ComponentScan(basePackages={"com"}) @ServletComponentScan //scans from the package of the annotated class (@WebServlet, @WebFilter, and @WebListener) @EnableScheduling //启用定时器功能 public class DemoApplication { public static void main(String[] args) { //此设置一定要在SpringApplication.run(DemoApplication.class, args); 前面进行设置 //System.setProperty("spring.devtools.restart.enabled","false"); SpringApplication.run(DemoApplication.class, args); } }
2.定时器任务类
@Component public class MyScheduler { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); //每隔2秒执行一次 @Scheduled(fixedRate = 2000) public void testTasks1() { System.out.println("定时任务执行时间:" + dateFormat.format(new Date())); } //每天3:05执行 @Scheduled(cron = "0 05 03 ? * *") public void testTasks() { System.out.println("定时任务执行时间:" + dateFormat.format(new Date())); } }