在程序入口启动类添加@EnableScheduling
,开启定时任务功能
@SpringBootApplication @EnableScheduling public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
定义定时任务逻辑
@Component public class SyncDatabase { // Seconds Minutes Hours DayofMonth Month DayofWeek Year // Seconds Minutes Hours DayofMonth Month DayofWeek @Scheduled(cron="0 * * * * *") public void sync(){ System.out.println("sync database"); } // fixedRate 即使上一次调用还在运行,也使Spring运行任务 // fiexedDelay 距离上一次任务执行完成间隔时间 @Scheduled(fixedRate=1000 * 2) public void async(){ System.out.println("async database"); } }