java - 后台 worker 的Spring Boot应用程序

标签 java spring spring-boot backgroundworker runnable

我定义了以下 Spring boot 应用程序:

@SpringBootApplication
public class Application implements CommandLineRunner {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(WebApplicationType.NONE).run(args);
    }

    public void run(String... args) throws Exception {
        Thread.currentThread().join();
    }
}

我还有一个 worker 包(即可以是实现 Runnable 的类)。它们应该无限期地运行。

运行它们的“Spring 方式”是什么? (并且在没有明确知道他们的情况下自动这样做)

谢谢

最佳答案

and doing so automatically, without explicitly knowing them

没有从特定位置自动运行某些 Runnable 的机制。您需要找到一种方法来通知 Spring 这些类。

三种常见场景:

  1. 在应用程序启动期间执行一些代码:ApplicationRunnerCommandLineRunner .

您要么聚集 Runnable 并将它们包装到一个 [Application|CommandLine]Runner 中,它应该是一个 bean(例如 @Bean@Component 等)或使每个 Runnable 成为一个单独的 [Application|CommandLine]Runner

  1. 在某个时间点执行一些代码:TaskExecutor .

您注入(inject)一个 TaskExecutor 并为其提供之前收集的 Runnable

  1. 重复执行一些代码:TaskScheduler .

您注入(inject)一个 TaskScheduler 并为其提供之前收集的 Runnable,加上 a trigger .

更多详情:Task Execution and Scheduling

关于java - 后台 worker 的Spring Boot应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53363433/

相关文章:

java - 在 application.properties 评估之前将环境属性添加到 @SpringBootTest ?

使用 JAXB 基于条件的 Java spring XML 绑定(bind)

当 id 为 String 时,Java mongoTemplate findOne 查询不返回结果

java - OpenGL - 使用 GL11 的 OS X

drupal - 为什么 springsource.com 网站是用 drupal 构建的?

spring - 模拟 Keycloak token 以测试 Spring Controller

java.sql.SQLException : Access denied for user '' @'localhost' (using password: NO) with Spring+JPA+ MySql 异常

java - 如何在 hibernate 中正确映射枚举集合?

java - 在 Java 中连接 RowFilter orFilters 与 andFilter

java - 从 EventHostProcessor 中的最后一个检查点重新开始消费