Search code examples
javaspringspring-bootscheduled-tasks

A application have multiple instances. There is a Job which will be running in a specific time. how can i make job run by only one instance?


We have an vertical scaling application (Say there are 5 instances) and application do have one schedular job which executes every hour to send an email to customer. due to multiple instances it will send a multiple emails.

Is there any framework in java/spring by which only any one instance at a time only one schedular will run? how it can be handled in a multi instances.


Solution

  • Is there any framework in java/spring by which only any one instance at a time only one schedular will run?

    Yes. I see you are using Spring Boot. Spring Boot supports using the Quartz Scheduler for scheduled jobs. After enabling the Quartz Scheduler in Spring Boot, by adding the spring-boot-starter-quartz dependency, you can take the extra step to configure Quartz to use your database as a job store, with the setting spring.quartz.job-store-type=jdbc.

    Once you have done those things, you can then define a scheduled Quartz job, and Quartz will use locks in your database to ensure it runs on only one instance of your Spring Boot application.

    There's a good tutorial on this here.