@SpringBootApplication @EnableScheduling public class ScheduledTest { public static void main(String[] args) { SpringApplication.run(ScheduledTest.class); } }
@Slf4j @Component public class ScheduledTasks { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(cron = "0/2 * * * * ? ") public void task1() { log.info("定时任务1,每2秒执行一次,time: {}", dateFormat.format(new Date()) + " 线程:" + Thread.currentThread().getName()); } }
@Configuration @Component @Slf4j public class TestTask implements SchedulingConfigurer { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.addFixedDelayTask(this::index2, 1000); } public void index2() { log.info("定时任务2,每1秒执行一次,time:" + dateFormat.format(new Date()) + " 线程:" + Thread.currentThread().getName()); } }
多处部署的问题:每处都会执行一次定时任务。
考虑使用支持分布式的定时任务实现。