The scheduler works fine with single instance/node. But when we scale up our application more than one node. In this case, we are seeing scheduler will run on every node.
Ex- we deployed our application at 3 nodes. In this schedule job will run all three nodes. For resolving this issue, spring boot will provide Shedlock in scheduler.
you can use shedlock in your application with given steps.
Step 1: Add given dependency in pom.xml file
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-spring</artifactId>
<version>5.9.1</version>
</dependency>
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-provider-jdbc-template</artifactId>
<version>5.9.1</version>
</dependency>
Step 2: Need to create table for shedLock to keep scheduler lock information
CREATE TABLE shedlock (
name VARCHAR(64),
lock_until TIMESTAMP(3) NULL,
locked_at TIMESTAMP(3) NULL,
locked_by VARCHAR(255),
PRIMARY KEY (name)
)
Step 3: Let create config class for lockProvider.
@EnableSchedulerLock(defaultLockAtMostFor = "PT30S")
@Configuration
public class SchedulerConfiguration {
@Bean
public LockProvider lockProvider(DataSource dataSource) {
return new JdbcTemplateLockProvider(dataSource, "shedlock");
}
@Bean
public ScheduledLockConfiguration scheduledLockConfiguration(LockProvider lockProvider) {
return ScheduledLockConfigurationBuilder
.withLockProvider(lockProvider)
.withPoolSize(10)
.withDefaultLockAtMostFor(Duration.ofMinutes(10))
.build();
}
}
Step 4: Add @EnableScheduling and @EnableSchedulerLock annotations on our spring configuration class
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Step 5: Now create a TASK
@Scheduled(cron = "0 * * * * *")
@SchedulerLock(name = "nameOfScheduler", lockAtMostFor = "FIVEMIN, lockAtLeastFor = FIVEMIN)
public void shortRunningTask() {
System.out.println("Start short running task");
}
That’s all.
NOTE: – Please make sure both nodes are running same time zone.