Search code examples
spring-bootschedulingspring-scheduled

How to create multiple instances of a scheduler class in spring boot?


I have a class containing the @Scheduled annotated method. I want to create multiple instances of a class in spring boot application so that I should be able to run multiple jobs for the specified time period.

I have googled and tried with creating a new object but scheduling didn't work.

Note: I will pass what to execute at runtime for respective instance.


Solution

  • Here is the answer, I implemented ApplicationContextAware

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        for (int i =0;i<4;i++) {
        ((ConfigurableApplicationContext) applicationContext).getBeanFactory()
            .registerSingleton("New Instance " + i, new SchedularJob());
        }
    }
    

    It will create 4 instances of SchedularJob class and 4 schedulers will run independently.