在群集环境中运行的Spring Scheduled Task [英] Spring Scheduled Task running in clustered environment
问题描述
我正在编写一个具有cron作业的应用程序,该作业每60秒执行一次.该应用程序被配置为在需要时扩展到多个实例.我只想每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屋!