我定义了以下 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 这些类。
三种常见场景:
- 在应用程序启动期间执行一些代码:
ApplicationRunner
和CommandLineRunner
.
您要么聚集 Runnable
并将它们包装到一个 [Application|CommandLine]Runner
中,它应该是一个 bean(例如 @Bean
、@Component
等)或使每个 Runnable
成为一个单独的 [Application|CommandLine]Runner
。
- 在某个时间点执行一些代码:
TaskExecutor
.
您注入(inject)一个 TaskExecutor
并为其提供之前收集的 Runnable
。
- 重复执行一些代码:
TaskScheduler
.
您注入(inject)一个 TaskScheduler
并为其提供之前收集的 Runnable
,加上 a trigger .
关于java - 后台 worker 的Spring Boot应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53363433/