第一步:再啓動方法上添加註解,打開定時總開關
@EnableScheduling加在@SpringBootApplication註解的啓動類上,表示啓動總開關
@SpringBootApplication @EnableScheduling public class DreamApplication { public static void main(String[] args) { SpringApplication.run(DreamApplication.class, args); System.out.println("程序啓動成功!"); } }
第二不:單獨給方法添加配置。要注意類上加註解@Component,方法上加註解@Scheduled
@Component public class demo { @Scheduled(cron = "0/5 * * * * ?") public void job(){ System.out.println("每五秒執行一次"); } }
擴展:@SpringBootApplication是一個組合註解,由@Configuration,@EnableAutoConfiguration和@ComponentScan組成