如何使用@PostConstruct 仅在一个实例中调用@Scheduled 方法 [英] How to call @Scheduled method in only one instance using @PostConstruct

查看:211
本文介绍了如何使用@PostConstruct 仅在一个实例中调用@Scheduled 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 有工作需要按 cron 计划完成
  2. 必须在spring boot应用程序启动时执行与作业中相同的逻辑,因此使用@PostConstruct方法
  3. 使用了 Shedlock,因为它计划在多个实例中运行应用程序

问题是:如何让@PostConstruct 方法的逻辑只在一个实例中调用而在其他实例中不调用?

The question is: how to make the logic from the @PostConstruct method be called in only one instance and not called in others?

我的代码示例:

@Component
@AllArgsConstructor
public class TestJob {

    private TestService testService;

    @PostConstruct
    public void init() {
        testService.upload();
    }
    
    @Scheduled(cron = "${cron}")
    @SchedulerLock(name = "uploadJob", lockAtMostFor = "${lockAtMostFor}")
    public void execute() {
        testService.upload();
    }
}

推荐答案

如果您将 @PostConstruct 方法放在不同的服务并调用 execute() 方法,它应该可以工作> 方法.

It should work if you put the @PostConstruct method to a different service and call the execute() method.

原因是 ShedLock 默认使用 Spring AOP,它将 @SchedulerLock 标记的每个方法包装在一个方面进行锁定.如果在同一个类中调用另一个方法,通常不会应用 Spring AOP.

The reason is that ShedLock by default uses Spring AOP which wraps each method marked by @SchedulerLock in an aspect that does the locking. And Spring AOP usually does not get applied if you call another method in the same class.

这篇关于如何使用@PostConstruct 仅在一个实例中调用@Scheduled 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆