集群环境下运行的Spring Scheduled Task [英] Spring Scheduled Task running in clustered environment
问题描述
我正在编写一个应用程序,它有一个每 60 秒执行一次的 cron 作业.应用程序配置为在需要时扩展到多个实例.我只想每 60 秒(在任何节点上)在 1 个实例上执行任务.开箱即用的我找不到解决方案,我很惊讶之前没有多次询问它.我使用的是 Spring 4.1.6.
I am writing an application that has a cron job that executes every 60 seconds. The application is configured to scale when required onto multiple instances. I only want to execute the task on 1 instance every 60 seconds (On any node). Out of the box I can not find a solution to this and I am surprised it has not been asked multiple times before. I am using Spring 4.1.6.
<task:scheduled-tasks>
<task:scheduled ref="beanName" method="execute" cron="0/60 * * * * *"/>
</task:scheduled-tasks>
推荐答案
有一个 ShedLock正是为此目的服务的项目.您只需注释执行时应锁定的任务
There is a ShedLock project that serves exactly this purpose. You just annotate tasks which should be locked when executed
@Scheduled( ... )
@SchedulerLock(name = "scheduledTaskName")
public void scheduledTask() {
// do something
}
配置 Spring 和 LockProvider
Configure Spring and a LockProvider
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "10m")
class MySpringConfiguration {
...
@Bean
public LockProvider lockProvider(DataSource dataSource) {
return new JdbcTemplateLockProvider(dataSource);
}
...
}
这篇关于集群环境下运行的Spring Scheduled Task的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!