简体   繁体   English

Spring 引导应用程序定期运行方法

[英]Spring Boot application run method periodically

I am playing with a simple Spring Boot application and RabbitMQ.我正在玩一个简单的 Spring 引导应用程序和 RabbitMQ。

However I cannot figure out how to run a method periodically.但是我无法弄清楚如何定期运行方法。

Here is my Application class这是我的应用程序 class

@SpringBootApplication
public class SampleApp {
    @Autowired
    Sender sender;

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

    @EventListener(ApplicationReadyEvent.class)
    public void doSomethingAfterStartup() {
        sender.sendMessage();
    }
}

And the sendMessage method is defined as below sendMessage方法定义如下

@Scheduled(fixedRate = 3000L)
public void sendMessage() {
    log.info("Sending message...");
    rabbitTemplate.convertAndSend("my-exchange", "my-routing-key", "TEST MESSAGE");
}

However this method is called only once, I can see only a single line in the console.但是这个方法只被调用一次,我在控制台中只能看到一行。

What I missed in my code?我在代码中遗漏了什么?

Thanks.谢谢。

Looks like you are missing @EnableScheduling :看起来您缺少@EnableScheduling

@EnableScheduling
@SpringBootApplication
public class SampleApp {
    ...
}

Quoting the documentation:引用文档:

Enables Spring's scheduled task execution capability, similar to functionality found in Spring's <task:*> XML namespace.启用 Spring 的计划任务执行功能,类似于 Spring 的<task:*> XML 命名空间中的功能。 To be used on @Configuration classes as follows:用于@Configuration类,如下所示:

 @Configuration @EnableScheduling public class AppConfig { // various @Bean definitions }

This enables detection of @Scheduled annotations on any Spring-managed bean in the container.这可以检测容器中任何 Spring 管理的 bean 上的@Scheduled注释。

I am usually using the Spring ThreadPoolTaskScheduler .我通常使用 Spring ThreadPoolTaskScheduler Scheduler 。 You define it, as Bean for example then you wrap your method into a Runnable and you call it at intervals defined by a CronTrigger .您将它定义为 Bean 例如,然后将方法包装到Runnable中,并按CronTrigger定义的间隔调用它。 The result can be retrieved using a ScheduledFuture可以使用ScheduledFuture检索结果

Check https://www.baeldung.com/spring-task-scheduler for a complete beginner tutorial.查看https://www.baeldung.com/spring-task-scheduler以获得完整的初学者教程。

Here's an alternative way if you don't want to rely on Spring's scheduler.如果您不想依赖 Spring 的调度程序,这是另一种方法。

It's using rxjava2, here's an example:它使用 rxjava2,这里有一个例子:

@Component
public class MessagePublisher {

  Sender sender;
  Disposable d;

  @Autowired
  public Config(Sender sender) {
    this.sender = sender;
    this.d = doSomethingAfterStartup();
  }

  public Disposable doSomethingAfterStartup() {
    return Observable.interval(3000, TimeUnit.MILLISECONDS).subscribe(tick -> {
      sender.sendMessage();
     });
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM