如何在 Spring Boot 中安排任务

问题描述 投票:0回答:0

按照这个 guide 我设置了一个基本的 Spring 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");
    }
}
java spring-boot scheduled-tasks
© www.soinside.com 2019 - 2024. All rights reserved.