介绍下@Scheduled的实现原理以及用法
典型回答 Spring 的 @Scheduled 注解用于在 Spring 应用中配置和执行定时任务。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class ScheduledTasks { // 每隔5秒执行一次 @Scheduled(fixedRate = 5000) public void performTask() { System.out.println("fixedRate task " + System.currentTimeMillis()); } // 上一个任务完成后等待5秒再执行 @Scheduled(fixedDelay = 5000) public void performDelayedTask() { System.out.println("fixedDelay task " + System.currentTimeMillis()); } // 每天晚上12点执行 @Scheduled(cron = "0 0 0 * * ?") public void performTaskUsingCron() { System.out.println("corn task " + System.currentTimeMillis()); } } Spring 的定时任务调度框架在 spring-context 包中,所有的类都在 scheduling 包中: ...