Search code examples
springasynchronoustaskscheduling

Spring @Schleduled annotation does not work


I want a spring scheduled task, that runs every 10 seconds, however for some reason the task runs only once and is never repeated again.

Please do not suggest me to use other types of tasks, because I need specifically to use spring tasks.

@Scheduled(fixedRate = 10000, initialDelay = 1000)
public void myTask() {
...
}

In my main config class I have @EnableScheduling added as well.


Solution

  • Scheduling is a process of executing the tasks for a specific time period, but you looking to make it asynchrounslly so there will be a couple of changes

    create a config class that will manage the Async operations so you make use of ThreadPoolTaskExecutor:

    @EnableScheduling
    @Configuration
    public class TaskConfig implements SchedulingConfigurer {
    
        @Override
        public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar)
        {
            ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
            threadPoolTaskScheduler.setPoolSize(10);
            threadPoolTaskScheduler.setThreadNamePrefix("your-scheduler-");
            threadPoolTaskScheduler.initialize();
    
            scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
        }
    }
    

    then you can run jobs asynchrounslly as the below :

    @Component
    public class HelloSender {
    
        @Scheduled(fixedRate = 10000)
        public void myTask() {
    
            System.out.println("im running asynchronous with Worker : " + Thread.currentThread().getName());
        }
    }
    

    for further information about ThreadPoolTaskExecutor please have look here: https://docs.spring.io/spring-framework/docs/3.0.x/spring-framework-reference/html/scheduling.html