Run Spring Scheduled jobs configured in different modules

Viewed 931

I have a Spring Boot application where I am using the Spring scheduling to schedule cron jobs. I have 3 different modules in my application: service-toolA, service-toolB and service-application.

My service-application module has the Spring-Boot config and the Application class as follows:

package com.service.tool.main;

@SpringBootApplication
@ComponentScan("com.service.tool")
@EnableAsync
@EnableScheduling 
public class Application {

    public static void main(String args[]) {
        SpringApplication.run(Application.class);
    }
 }

Now I have my Scheduled jobs in the other modules service-toolA and service-toolB. I have configured them as follows:

@Scheduled(fixedRate = 4000)
public void printName() {
   System.out.println("Hello World");
}

However when I run the application, the Scheduled jobs doesn't get started. They run when I place these Scheduled methods in the service-application module where my Application class is present.

How do I run it in different modules and the config being in service-application module?

3 Answers
@Configuration

I solved it by adding this annotation.

Mark your class as @Service attribute

@Service
public class ScheduledTasks {

   @Scheduled(fixedRate = 4000)
   public void printName() {
      System.out.println("Hello World");
   }

}

Then add package name in @ComponentScan

@ComponentScan({"service-toolA", "service-toolB"})
...
public class Application {

    public static void main(String args[]) {
        ...
    }
 }
Related