Spring boot application for background workers

血红的双手。 提交于 2020-01-24 10:04:26

问题


I have defined the following Spring boot application:

@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();
    }
}

I also have a package of workers (i.e. could be classes which implements Runnable). They are supposed to run indefinitely.

What is the "Spring way" to run them? (and doing so automatically, without explicitly knowing them)

Thanks


回答1:


You could (1) have your classes that implement Runnable be annotated with @Component, so that Spring can find them. You can then (2) write a WorkManager, annotated with @Service, with an @Autowired List - which Spring would initialize with a list instances of all your classes from (1). And could (3) write a @PostConstruct method in your WorkManager that would iterate over that list of Runnables, and pass each one to a TaskExecutor to run...




回答2:


and doing so automatically, without explicitly knowing them

There's no mechanism to automatically run some Runnables from a certain place. You need to find a way to inform Spring about these classes.

Three common scenarios:

  1. Execute some code during the application startup: ApplicationRunner and CommandLineRunner.

You either congregate Runnables and wrap them up into an [Application|CommandLine]Runner which should be a bean (e.g. @Bean, @Component, etc) or make each Runnable a separate [Application|CommandLine]Runner.

  1. Execute some code at some point of time: TaskExecutor.

You inject a TaskExecutor and give it previously gathered Runnables.

  1. Execute some code repeatedly: TaskScheduler.

You inject a TaskScheduler and give it previously gathered Runnables, plus a trigger.

More details: Task Execution and Scheduling



来源:https://stackoverflow.com/questions/53363433/spring-boot-application-for-background-workers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!