Add Package
<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.2
.
0
</version>
</dependency>
Add Table
CREATE TABLE `shedlock` (
`name` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
`lock_until` timestamp(3) NULL DEFAULT NULL,
`locked_at` timestamp(3) NULL DEFAULT NULL,
`locked_by` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Add config
import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;
import net.javacrumbs.shedlock.spring.ScheduledLockConfiguration;
import net.javacrumbs.shedlock.spring.ScheduledLockConfigurationBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import javax.sql.DataSource;
import java.time.Duration;
@Configuration
@EnableScheduling
public class ShedlockConfig {
@Bean
public LockProvider lockProvider(DataSource dataSource) {
return new JdbcTemplateLockProvider(dataSource);
}
@Bean
public ScheduledLockConfiguration scheduledLockConfiguration(LockProvider lockProvider) {
return ScheduledLockConfigurationBuilder
.withLockProvider(lockProvider)
.withPoolSize(10)
.withDefaultLockAtMostFor(Duration.ofMinutes(10))
.build();
}
}
具体的定时任务
import net.javacrumbs.shedlock.core.SchedulerLock;
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "PT30S") //重点地方
public class MarkRefreshScheduler {
Final static Logger = Logger Private LoggerFactory.getLogger (MarkRefreshScheduler.class);
// Monday morning 5:00 once, the user identifies the hot heat value and zero
@Scheduled (cron = "0 0/2 * * *?")
@SchedulerLock (name = "headNumCronName", lockAtMostFor = 5 * 1000, lockAtLeastFor = 5 * 1000) // focus on local
public void refreshHotSumAndIsOnTop () {
logger.info ( "the begin refreshHotSumAndIsOnTop ...");
// do something
Logger. info ( "refreshHotSumAndIsOnTop the begin ...");
}
}
results
Lock achieved by modifying the data in the database tables
There are four fields
Primary key name: a name of each timed task
locked_at: Lock start time
End Time lock: lock_until
When the timer starts again, it will update both time and timing of the time will not be executed