Spring Boot 如何在Sping Boot 中计划任务

l3zydbqr  于 2023-03-02  发布在  Spring
关注(0)|答案(1)|浏览(207)

guide之后,我设置了一个基本的Sping Boot Scheduler,当我运行下面的SchedulingTasksApplication时,它会像预期的那样重复打印日志。

ScheduledTasks

  1. package com.climate.schedulingtasks;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.scheduling.annotation.Scheduled;
  7. import org.springframework.stereotype.Component;
  8. @Component
  9. public class ScheduledTasks {
  10. private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
  11. private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
  12. @Scheduled(fixedRate = 5000)
  13. public void reportCurrentTime() {
  14. log.info("The time is now {}", dateFormat.format(new Date()));
  15. }
  16. }

SchedulingTasksApplication

  1. package com.climate.schedulingtasks;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.scheduling.annotation.EnableScheduling;
  5. @SpringBootApplication
  6. @EnableScheduling
  7. public class SchedulingTasksApplication {
  8. public static void main(String[] args) {
  9. SpringApplication.run(SchedulingTasksApplication.class);
  10. }
  11. }

然后我添加了一个ProducerService来生成5条消息,我尝试添加符号来连接到SchedulingTasksApplication,但是当我运行它时,我从来没有看到调用ProducerService

ProducerService

  1. package com.climate.eventplatform.client.jobs.heartbeat;
  2. import com.climate.eventplatform.client.EventPlatformClientException;
  3. import com.climate.schedulingtasks.ScheduledTasks;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.scheduling.annotation.Scheduled;
  7. import org.springframework.stereotype.Component;
  8. import java.io.IOException;
  9. @Component
  10. public class ProducerService {
  11. private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
  12. @Scheduled(fixedRate = 5000)
  13. public static void main(String[] args) throws EventPlatformClientException, InterruptedException, IOException {
  14. HeartBeatProducer.produceAll("Producer 1");
  15. log.info("Producer Running");
  16. }
  17. }
vsikbqxv

vsikbqxv1#

默认情况下,spring-boot将扫描并注册@SpringBootApplication类的包的所有子包下的bean(更多细节请参见本文)
现在您的@SpringBootApplication位于com.climate.schedulingtasks包中,但ProducerService位于com.climate.eventplatform.client.jobs.heartbeat包中,而com.climate.eventplatform.client.jobs.heartbeat包不在com.climate.schedulingtasks包下,因此无法扫描。
您可以像注解中提到的那样明确指定要扫描的所有包,或者只是将ProducerService移动到com.climate.schedulingtasks下的任何包

相关问题