How do you separate roles in Spring Boot ? (Web vs Scheduler, etc..)

Viewed 101

I am coming from a (mostly) Python Django/Celery background and starting with Spring Boot.

I am having a hard time to understand how do you separate the roles.

For example when having a Django/Celery project, I will have one one side the web backends started as gunicorn, and on the other side the workers started as celery (so, different commands, but pointing at the same code).

But on Spring Boot, you only have a single entrypoint, and as soon as the scheduler is injected, the jobs will start being processed.

What is the correct way do separate those like in a Django/Celery application ? Should I put almost all my code as a library and then create 2 final applications, one that will setup the @DispatcherServlet and another one that will setup @EnableScheduling, or is there some kind of configuration to be injected at runtime ?

1 Answers

In my opinion, if 'the web' and 'the scheduler' are both the important function in the application, then we don't need to separate them as long as you are creating a monolithic application.

Because you are using spring boot, so @DispatcherServlet and all the other web component that a web application needed will be injected and configured automatically. The only thing you have to do is creating some class that annotated with @Controller or @RestController and set up the @RequestMapping methods inside those class.

How about Scheduler? you need to add @EnableScheduling in one of the @Configuration class first, then create Scheduler class in scheduler package like below code sample.

You can use cron property to set up the specify execute time just like Linux crontab. The jobs will start being processed only if the cron time is up.

@Component
public class PlatformScheduler {

    @Autowired
    private BatchService batchService;
   
    @Scheduled(cron = "0 0 12 * * *")
    public void dailyInitialize() {

        clearCompletedBatches();
        queryBatchesToRunToday();

    }


    @Scheduled(fixedRate = 10000, initialDelay = 10000)
    private void harvestCompletedBatches() {

        batchService.harvestCompletedBatches();

    }

    @Scheduled(fixedRate = 10000, initialDelay = 10000)
    private void executeWaitingBatches() {

        batchService.executeWaitingBatches(new DateTime());

    }

}

The most simple project hierarchy will be like below, 'the web' and 'the scheduler' can be in the same project safely and share the same @Service components without harm.

enter image description here

Related