简体   繁体   中英

Execute task async in DB on Spring startup

I'm trying to make my spring boot application start without connection to the db. The approach in this question seems to be very promising, however, my application executes a CommandLineRunner which does some db maintainance (verifying that all indices are in place etc.) on startup. In order to avoid getting timeouts there, I tried to run the CommandLineRunner method asynchronously (using Spring's @Async ), trying to get a db connection until it succeeds, but I'm still getting timeout exceptions. I assume that async execution of the CommandLineRunner method doesn't work.

Any hints on this?

You could refactor to make the whatever functionality is within the CommandLineRunner be scheduled with a TaskScheduler , and schedule it enough time in the future to avoid the timeouts. On failure you could gracefully shutdown the spring boot application if the maintenance isn't ran as expected.

https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-task-scheduler

The simplest method is the one named 'schedule' that takes a Runnable and Date only. That will cause the task to run once after the specified time . All of the other methods are capable of scheduling tasks to run repeatedly. The fixed-rate and fixed-delay methods are for simple, periodic execution, but the method that accepts a Trigger is much more flexible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM