Persisting the task status in the database is one of the core features of Spring Cloud Task. If you don't need that, you most likely don't need Spring Cloud Task.
If you have the web dependency on the classpath (e.g. for the actuators), the application will only stop when the embedded web server is stopped. If the web server has been started by Spring, a good way to do this here is to close the application context, which takes care of the rest.
If your task is executed from an ApplicationRunner
, you can listen for the ApplicationReadyEvent
that is only sent after all runners have finished. In the listener for this event you can then close the application context.
This could roughly look like this:
@SpringBootApplication
public class DemoApplication {
private static final Logger LOG = LoggerFactory.getLogger(DemoApplication.class);
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
ApplicationRunner applicationRunner() {
return args -> LOG.info("Hello Task");
}
@Component
static class ShutdownWhenReadyListener implements ApplicationContextAware, ApplicationListener<ApplicationReadyEvent> {
private ConfigurableApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
context = (ConfigurableApplicationContext) applicationContext;
}
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
context.close();
}
}
}
For very simple apps, you can also close the application context directly from main as the method run
will only return after the context is fully booted which includes all ApplicationRunners
to have run:
@SpringBootApplication
public class DemoApplication {
private static final Logger LOG = LoggerFactory.getLogger(DemoApplication.class);
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args).close();
}
@Bean
ApplicationRunner applicationRunner() {
return args -> LOG.info("Hello Task");
}
}