Search code examples
springmultithreadingspring-bootthreadpool

Running scheduler in Spring boot is spawning a process external to Spring boot application context


I am scheduling a task that runs at fixed rate in Spring boot. The function that I am using to schedule a a task is as below:

private void scheduleTask(Store store, int frequency) {
        final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        Runnable task = store::scan;
        scheduler.scheduleAtFixedRate(task, 0, frequency, TimeUnit.MILLISECONDS);
    }

This works fine but if if there is an exception at application startup, the application should exit on exception. What is happening is that I get the exception in the log and the message "Application Failed to start" but looks like the scheduler shows as still running although it looks like only the scheduled thread is still running.

Any hints on how to properly schedule an asynchronous task in a Spring boot application? I tried the @Scheduled annotation but it does not run at all.


Solution

  • The @Scheduled should work. Have you added the @EnabledScheduling annotation to a @Configuration or the @SpringBootApplication? The Scheduling Getting Started explains it in detail.

    Regarding the scheduleTask method: What calls that? Is it started outside the Spring context? If yes then Spring won't stop it. You have to take care of the lifecycle.

    You should try to use the @Scheduled as it will manage the thread pools/executors for you and most people will find it easier to understand.