Home > Software engineering >  Is it possible/advisable to run Spring Boot without controllers just for the @ScheduledTasks and ORM
Is it possible/advisable to run Spring Boot without controllers just for the @ScheduledTasks and ORM

Time:10-12

I'd like to run a Spring Boot service without any of the controller-related stuff. I'd like it to just run a scheduled task every hour and do work if needed. I'm wanting to use Spring Boot, because I already know how to set the Hibernate ORM up, and I'm re-using a lot of the same repositories as another Spring Boot service. So, I spun up a new Spring Boot project and left out the start-web package.

The main issue I'm running into is that despite having a scheduled task set up, the service starts and immediately quits without running the scheduled task. In my head, I imagined the service kind of just sitting there, running, waiting for the time to trigger the scheduled job I have configured and kind of just sleeping until then. Are my expectations bad, or do I just have it misconfigured?

CodePudding user response:

Yes, it is possible. You can use profiles to mark the beans (controllers, components, etc...)

@Controller
@Profile("controllers")
public class OneController {
....
}

@ScheduledTask
@Profile("tasks")
public class OneTask {
....
}

Then start the application with the required profile activated by the command line:

java ... -Dspring.profiles.active=controllers

Or by an environment variable:

export spring_profiles_active=controllers

Even both at the same time:

export spring_profiles_active=controllers,tasks

More details here: https://www.baeldung.com/spring-profiles

CodePudding user response:

You can either remove spring-boot-starter-web from your dependencies or in your main class you can configure the SpringApplicationBuilder to not include the web server.

new SpringApplicationBuilder(YourApplication.class)
  .web(WebApplicationType.NONE)
  .run(args);
  • Related