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

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

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

ScheduledTasks

package com.climate.schedulingtasks;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTasks {

    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        log.info("The time is now {}", dateFormat.format(new Date()));
    }
}

SchedulingTasksApplication

package com.climate.schedulingtasks;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class SchedulingTasksApplication {

    public static void main(String[] args) {
        SpringApplication.run(SchedulingTasksApplication.class);
    }
}

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

ProducerService

package com.climate.eventplatform.client.jobs.heartbeat;

import com.climate.eventplatform.client.EventPlatformClientException;
import com.climate.schedulingtasks.ScheduledTasks;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ProducerService {

    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    @Scheduled(fixedRate = 5000)
    public static void main(String[] args) throws EventPlatformClientException, InterruptedException, IOException {
        HeartBeatProducer.produceAll("Producer 1");
        log.info("Producer Running");
    }
}
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下的任何包

相关问题