Home > Mobile >  Best approach implementing server-side logic with some sort of TaskManager class
Best approach implementing server-side logic with some sort of TaskManager class

Time:01-26

I'm usually coding in Node, but want to try Spring Boot and before I start a project I want to build, I wanted to ask for best approaches to save time.

My project requires some sort of Manager class that manages a set of custom classes I am going to code, for example an AnimalManager that manages a bunch of Animal.class objects.

All Animals are using websockets to receive data from third party APIs. I need some Manager class to handle all these Animals and call their functions based on custom intervals etcetera.

What I am confused about now is how to implement such Manager classes that need to start working after start up without instantiation. From my understanding @Service is more like business logic for database operations. Is there some equivalent for Manager classes or standalone classes that don't interact with databases or controllers and are meant to just run tasks?

CodePudding user response:

You can use Spring's CommandLineRunner. It will be executed after startup when everything is initialized and ready. See: https://www.baeldung.com/spring-boot-console-app

@SpringBootApplication
public class Application implements CommandLineRunner {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
 
    @Override
    public void run(String... args) {
        // TODO implementation of your task manager
    }
}

CodePudding user response:

I don't really know if the manager runs continuously or not (in a loop), also if the animals are hard coded or not and if those intervals are configurable at runtime or not.. but perhaps this helps :

You could create a component (for your manager) with a @PostConstruct that start doing your stuff then (after bootup) https://www.baeldung.com/spring-postconstruct-predestroy.

You can also call methods at certain intervals with https://www.baeldung.com/spring-scheduled-tasks

It is also possible the animals don't need a Manager and are components that just react to incoming messages.

  • Related