Search results
Template to run Spring Boot Console applications indefinitely until graceful shutdown
@SpringBootApplication
@Slf4j
public class Application implements CommandLineRunner {
private volatile boolean keepRunning = true;
public static void main(String[] args) {
log.info("Started the console application");
SpringApplication.run(Application.class, args);
log.info("Exiting the console application");
}
@Override
public void run(String... args) throws Exception {
try {
synchronized (this) {
while (this.keepRunning) {
log.info("App is running, blocking main thread until a shutdown notification");
this.wait();
log.info("Exiting the run() method");
}
}
} catch (InterruptedException ex) {
log.warn("Main thread interrupted. {}", ExceptionUtils.getStackTrace(ex));
}
}
@PreDestroy
public void shutdown() {
synchronized (this) {
log.info("Notifying the app to stop running");
this.keepRunning = false;
this.notify();
}
}
}
This template Spring Boot application is useful for writing Quartz scheduler, or JMS, AWS SQS, Kafka, etc. Subscribers, Listeners, or Consumer applications.