0

I have spring application written in the following way -

@SpringBootApplication
@Import({
        ApplicationLoader.class
})
public class MyApplication {

    @Bean
    public Clock clock() {
        return Clock.systemDefaultZone();
    }

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

The ApplicationLoader class looks like below

public class ApplicationLoader {

    private final MyService myService;

    public ApplicationLoader(MyService myService) {
        // create
        this.myService = myService;
    }

    @PostConstruct
    void startJob() {
        // perform some long running task
        myService.runLongRunningTask();
    }
}

Once ApplicationLoader finishes its job, Spring Application continues to run while I want it to stop.

Is there a way I can introduce a stop to this entire application lifecycle which runs after the application is done performing the long running task? I don't mind a rewrite of ApplicationLoader or MyApplication if there is a better way. My aim is to instantiate MyService and run myService.runLongRunningTask() based on certain runtime conditions.

comiventor
  • 3,922
  • 5
  • 50
  • 77
  • 1
    Possible duplicate of [Programmatically shut down Spring Boot application](https://stackoverflow.com/questions/22944144/programmatically-shut-down-spring-boot-application) – Flown Dec 18 '17 at 06:50
  • You can use `ApplicationContext.close()` after initialization(Because your `longRunningTask` will run inside initialization of application). Though the design of your `longRunningTask` to run inside `@PostConstruct` is not good. – Zico Dec 18 '17 at 07:24
  • @Zico I too feel so intuitively because scheduling a task as part of an object construction doesn't look neat. Could you suggest a better alternative? – comiventor Dec 18 '17 at 07:28
  • Better to make the long running task asynchronous and start the task from somewhere(may be from main). And you can check the task is running or not by adding a flag in the service to decide to `close` the `context` or not – Zico Dec 18 '17 at 07:33
  • 2
    Don't include `spring-boot-starter-web` (I suppose that is what you have) if it isn't a web application. If you include it it will start a container en keep it running, if you don't it will start as a command line job do its thing and stop. Also shouldn't you be using Spring Batch instead of what you have now? – M. Deinum Dec 18 '17 at 07:34
  • @m-deinum I liked your answer. I don't think I asked a duplicate question but not sure if i need to change my wording. Could you at least post your comment as answer so that I can accept it. Also, if you can post sample code in your answer that would be helpful for others. – comiventor Dec 18 '17 at 09:54

0 Answers0