Shedlock has run duplicate when run multi instance

2.1k Views Asked by At

I am using shedlock to make sure only 1 Schedule Task can run at same time when I have multi instances

<dependency>
        <groupId>net.javacrumbs.shedlock</groupId>
        <artifactId>shedlock-spring</artifactId>
        <version>4.5.2</version>
    </dependency>
    <dependency>
        <groupId>net.javacrumbs.shedlock</groupId>
        <artifactId>shedlock-provider-jdbc-template</artifactId>
        <version>4.6.0</version>
    </dependency>

@Configuration
@EnableScheduling
@EnableSchedulerLock(
defaultLockAtMostFor = "${scheduled.task.lock.at.most}", 
defaultLockAtLeastFor = "${scheduled.task.lock.at.least}")
public class SchedulerConfig implements AsyncConfigurer, SchedulingConfigurer {

@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    // TODO Auto-generated method stub
    TaskScheduler scheduler = this.taskScheduler();
    taskRegistrar.setTaskScheduler(scheduler);
}

@Override
public Executor getAsyncExecutor() {
    Executor executor = this.taskScheduler();
    return executor;
}

// shedlock config
@Bean
public LockProvider lockProvider(DataSource dataSource) {
    return new JdbcTemplateLockProvider(dataSource);
}  
}

Here is my task

@Scheduled(cron = "0 36 16 * * ?") //
 @net.javacrumbs.shedlock.spring.annotation.SchedulerLock(name = "ms.template.scheduleTaskJob2")
public void scheduleTaskJob2() {
    // Mandatory information for logging
    String _id = "schedule-" + UUID.randomUUID().toString();
    ThreadContext.put("serviceMessageId", _id);

    logger.info("Cron Expression task called at the 0 second every minutes Execution Time - {}",
            dateTimeFormatter.format(LocalDateTime.now()));
}

But in both 2 instance of my app, the schedule task is execute, and This info is show in DB

ms.template.scheduleTaskJob2    26-MAR-20 04.51.00.001824000 PM 26-MAR-20 04.36.00.392858000 PM MB0001-PCHOBW41
ms.template.scheduleTaskJob2    26-MAR-20 04.51.00.004479000 PM 26-MAR-20 04.36.00.298564000 PM MB0001-PCHOBT97

Why this error is occur? Many thank!

2

There are 2 best solutions below

0
On

Please consult troubleshooting section https://github.com/lukas-krecan/ShedLock#troubleshooting

0
On

Sorry for my bad. I miss primary key when create Shedlock table.