Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to run a long task using Spring Boot?

I would like to run several long tasks with Spring Boot using a TaskExecutor. I want to have multiple rfid readers running and getting tags of items continuously. Then I need to use these tags to update the database. So far I have not been able to get the tasks running more than one time using Spring Boot. Is this possible?

I'm creating a @Component reader class. When creating I start the listener service and the listener to keep track of the tags. I have the startMessageService and the setReaderConfig methods. The first method I start the message listener service to receive the messages with the tag info from the reader when it comes in. The second method sets up the reader to read autonomously so when the tags go by the reader, the reader sends a message to the listener and I receive the message.

The run method basically keeps the reader going to read when the messages come in. But for some reason the code is not working how I want it to. As soon as the reader has a tag come by I should receive a message and I'm not.

At the bottom is my threadpooltaskexecutor bean.

I'm not sure what I'm missing.

@Component
@Scope("prototype")
public class AlienReader extends AlienClass1Reader implements 
TagTableListener, MessageListener, Runnable{
 private String ipaddress;
 private int port;
 private String username;
 private String password;
 int serviceport;

public AlienReader(String ipaddress, int port, String username, String pwd, 
int serviceport) throws UnknownHostException, AlienReaderException, 
InterruptedException{
    super(ipaddress, port);
    this.ipaddress=ipaddress;
    this.port=port;
    this.username=username;
    this.password=pwd;
    this.serviceport=serviceport;
    startMessageService();
    setReaderConfig();

}

}

@Bean
public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(15);
    executor.setMaxPoolSize(42);
    executor.setQueueCapacity(11);
    executor.setThreadNamePrefix("threadPoolExecutor-");
    executor.setWaitForTasksToCompleteOnShutdown(true);
    executor.initialize();
    return executor;
}
like image 954
Roro Avatar asked Aug 30 '18 20:08

Roro


People also ask

Is spring boot good for large projects?

Spring Boot works well with microservices. The Spring Boot artifacts can be deployed directly into Docker containers. However, some developers don't recommend the framework for building large and monolithic apps.

What are the disadvantages of using spring boot?

Disadvantages of Spring BootSpring Boot creates a lot of unused dependencies, resulting in a large deployment file; The complex and time-consuming process of converting a legacy or an existing Spring project to a Spring Boot application; Not suitable for large-scale projects.

Why spring boot is not suitable for large-scale projects?

Spring Boot is not suitable for large-scale projects because Spring Boot creates a lot of unused dependencies, resulting in large deployment files.

Is spring boot good for production?

Spring Boot has revolutionized the way production-ready applications are developed, allowing developers to focus more on the application logic rather than spending time on boilerplate code to handle the necessary configurations and dependencies to run the application.


1 Answers

Spring Boot doesn't impose any limits; if you can do it in Java or another language you should be able to do it with Java + Spring Boot.

What is Spring Boot

To be clear, Spring Boot is basically just a framework for building Spring projects, which were historically quite complex and had a lot of boiler plate code. You can make spring boot command line applications or web applications (which are more normal). I'm sure more options exist and are coming as well.

So, Spring Boot will give you a head start by easily exposing configuration from your applicaiton.properties file, automatically wiring up all your spring beans, setting up the wiring for your controllers, etc. But it doesn't limit the code you write; it just lessens it.

Your Question

You can use an executor service to run any number of long running tasks as long as your PC/server can handle them.

Here's a working spring boot example that runs two different tasks in parallel or a minute. They could last forever and do anything, and you can easily scale it to hundreds of tasks.

import org.apache.catalina.core.ApplicationContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(App.class, args);
        App app = run.getBean(App.class);
        app.run();
    }

    private void run() {
        Runnable r1 = () -> {
            for(int i = 0; i < 30; ++i) {
                System.out.println("task 1");
                try {Thread.sleep(1000);} catch(Exception ignored) {}
            }
        };

        Runnable r2 = () -> {
            for(int i = 0; i < 30; ++i) {
                System.out.println("task 2");
                try {Thread.sleep(1000);} catch(Exception ignored) {}
            }
        };

        //Create an executor service with 2 threads (it can be like 50
        //if you need it to be).  Submit our two tasks to it and they'll
        //both run to completion (or forever if they don't end).
        ExecutorService service = Executors.newFixedThreadPool(2);
        service.submit(r1);
        service.submit(r2);

        //Wait or completion of tasks (or forever).
        service.shutdown();
        try { service.awaitTermination(Integer.MAX_VALUE, TimeUnit.DAYS); }
        catch (InterruptedException e) { e.printStackTrace(); }
    }
}

More Information

  • You can schedule callables instead of runnables if you need to get results eventually and wait on them.
  • There are lots of variants of the executor service if you need scheduled tasks in addition to the long running ones.
  • You can use however many threads you need; just increase the 10 :).
  • This particular app may be better as a command line one - but I made it the normal spring boot web type in case you needed controllers/etc to serve up task checking endpoints or whatever. Its pretty irrelevant as you're mainly asking about the tasks themselves. This app won't terminate once done though unless you add a System.exit() as its expecting to be a long lived web-app.
like image 111
John Humphreys Avatar answered Sep 21 '22 12:09

John Humphreys