- 有需要按 cron 计划完成的工作
- 必须在 spring boot 应用程序启动时执行与作业中相同的逻辑,因此使用 @PostConstruct 方法
- 使用 Shedlock,因为它计划在多个实例中运行应用程序
问题是:如何使 @PostConstruct 方法中的逻辑仅在一个实例中调用而不在其他实例中调用?
我的代码示例:
@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();
}
}