Eduardo
Eduardo

Reputation: 7141

Spring Boot Application with separate CommandLineRunner that shouldn't run when application starts

I have a springboot application in the form

src/main/java/example
 - Application.java
 - JobConfiguration.java
   scheduler
    - Job1.java
    - Job1Runner.java
    - Job2.java
    - Job2Runner.java

I like to be able to run my jobs on demand locally so I create a seperate Runner class for every job (e.g JobRunner.java) but currently when I run my Application class it also runs my Job1Runner class because it extends CommandLineRunner. Is there a way I can keep my runners seperate? (so the Application class doesnt run them, and the JobRunners dont run each other etc)

Application

@SpringBootApplication
public class Application {

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

JobConfiguration

@Configuration
@EnableScheduling
public class JobConfiguration implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        // Register jobs
    }

}

Example JobRunner

@SpringBootApplication(scanBasePackages = "com.example")
public class JobXRunner implements CommandLineRunner { // Where X is my job index

    @Autowired
    private final JobX job;

    @Override
    public void run(String... args) throws Exception {
        job.run();
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(JobXRunner.class, args);

    }
}

Upvotes: 3

Views: 1423

Answers (1)

Abhijit Sarkar
Abhijit Sarkar

Reputation: 24647

There are more than one ways to solve this problem:

  1. Create multiple profiles and assign them to the job runners. Activate one from command line using spring.profiles.active=jobrunner1, or spring.profiles.active=jobrunner1,jobrunner2 if you want to run more than one job. This solution lets you keep multiple CommandLineRunner implementations.
  2. Specify which class to run, which in turn depends on how you're executing the code. If running using an IDE or a build tool like Maven or Gradle, you'll have to specify the main class name since the default resolution won't work. See this thread for a Maven-specific solution. If you're running the jar, see this thread. CommandLineRunner has a main method, so you can keep them, or just convert to regular main classes.

Upvotes: 1

Related Questions