pradeep gk
pradeep gk

Reputation: 47

How to avoid duplication of scheduler tasks when deployed in multiple instances

Have a spring Boot application through which i am able to create a cron and schedule the tasks . However when the multiple instances of the app are deployed , the cron gets triggered in all the instances and results in duplication. Is there any configuration which needs to be done in spring level?

We are using redis and using a flag this can be controlled in other instances but need a better approach for resolving this issue. Tried even the redisson library which didnt help much.

Need to even consider the failover cases whenever a instance is down.Please help.

Thanks

Upvotes: 4

Views: 6912

Answers (1)

htshame
htshame

Reputation: 7330

Check out this article

Include in your pom.xml schedlock dependencies:

<dependency>
    <groupId>net.javacrumbs.shedlock</groupId>
    <artifactId>shedlock-spring</artifactId>
    <version>2.2.0</version>
</dependency>

<dependency>
    <groupId>net.javacrumbs.shedlock</groupId>
    <artifactId>shedlock-provider-jdbc-template</artifactId>
    <version>2.1.0</version>
</dependency>

Create shedlock table

CREATE TABLE shedlock(
  name VARCHAR(64),
  lock_until TIMESTAMP(3) NULL,
  locked_at TIMESTAMP(3) NULL,
  locked_by  VARCHAR(255),
  PRIMARY KEY (name)
)

And don't forget to add a name to each job you create.

@SchedulerLock(name = "job_name")

This way, when this job will be executed on multiple instances, job record will be added to shedlock table by the first instance, and all other instances will check shedlock table for existing records with needed job name. This way the job will be executed only once.

Upvotes: 3

Related Questions