javaspringshedlock

How can I configure multiple LockProvider for scheduled tasks in Spring?


I'm trying to create two shedlock configuration in Springboot to be able to lock my scheduled tasks using different tables

// Main lock provider
@Bean("mainLockProvider")
public LockProvider mainLockProvider(DataSource dataSource) {
    return new JdbcTemplateLockProvider(
            JdbcTemplateLockProvider.Configuration.builder()
                    .withJdbcTemplate(new JdbcTemplate(dataSource))
                    .usingDbTime()
                    .withTableName("main_shedlock_table")
                    .build());
}

// Secondary lock provider
@Bean("secondaryLockProvider")
public LockProvider secondaryLockProvider(DataSource dataSource) {
    return new JdbcTemplateLockProvider(
            JdbcTemplateLockProvider.Configuration.builder()
                    .withJdbcTemplate(new JdbcTemplate(dataSource))
                    .usingDbTime()
                    .withTableName("secondary_shedlock_table")
                    .build());
}

But it seems like it's not possible to specify which lock provider to use when defining my scheduled tasks, the @SchedulerLock annotation does not accept a LockProvider in it's parameter

@Scheduled(cron = "*/5 * * * *")
@SchedulerLock(name = "some_scheduled_task", lockAtLeastFor = "PT15S", lockAtMostFor = "PT1M")
public void scheduledTaskUsingMainLockProvider() {
  // Should have created a lock entry in table "main_shedlock_table"
}

@Scheduled(cron = "*/5 * * * *")
@SchedulerLock(name = "some_other_scheduled_task", lockAtLeastFor = "PT15S", lockAtMostFor = "PT1M")
public void scheduledTaskUsingSecondaryLockProvider() {
  // Should have created a lock entry in table "secondary_shedlock_table"
}

Is it possible to achieve what I'm trying to do ?


Solution

  • You can use the @LockProviderToUse annotation for that. Just add it next to the @SchedulerLock.

    @Scheduled(cron = "*/5 * * * *")
    @SchedulerLock(name = "some_scheduled_task", lockAtLeastFor = "PT15S", lockAtMostFor = "PT1M")
    @LockProviderToUse("mainLockProvider")
    public void scheduledTaskUsingMainLockProvider() {
      // Should have created a lock entry in table "main_shedlock_table"
    }
    
    @Scheduled(cron = "*/5 * * * *")
    @SchedulerLock(name = "some_other_scheduled_task", lockAtLeastFor = "PT15S", lockAtMostFor = "PT1M")
    @LockProviderToUse("secondaryLockProvider")
    public void scheduledTaskUsingSecondaryLockProvider() {
      // Should have created a lock entry in table "secondary_shedlock_table"
    }