Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot application for background workers

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

like image 873
yaseco Avatar asked Mar 06 '23 01:03

yaseco


2 Answers

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

like image 66
Andrew Tobilko Avatar answered Mar 31 '23 02:03

Andrew Tobilko


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...

like image 32
moilejter Avatar answered Mar 31 '23 02:03

moilejter