Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 7 of 10 · Caching, Async & Scheduling
Interview question

How do you prevent scheduled tasks from running on multiple instances (Distributed Locking)? शेड्यूल्ड टास्क्स को कई इंस्टेंस पर चलने से कैसे रोकें (डिस्ट्रिब्यूटेड लॉकिंग)?

Answer

@Scheduled runs independently on every JVM instance of an application, so a horizontally scaled service with 3 replicas would run the same scheduled job 3 times simultaneously by default — often causing duplicate emails, duplicate report generation, or race conditions on shared resources.

ShedLock is the standard solution: it uses a shared external store (a database table, Redis, or ZooKeeper) as a distributed lock, and only the instance that successfully acquires the lock for that execution window runs the task, while the others skip it. It's added declaratively with @SchedulerLock alongside the existing @Scheduled annotation, requiring minimal code changes.

@Scheduled(cron = "0 0 * * * *")
@SchedulerLock(name = "generateReport", lockAtMostFor = "10m", lockAtLeastFor = "1m")
public void generateReport() { ... }

@Scheduled डिफ़ॉल्ट रूप से किसी एप्लिकेशन के हर JVM इंस्टेंस पर स्वतंत्र रूप से चलता है, इसलिए 3 रेप्लिकास वाली एक हॉरिज़ॉन्टली स्केल्ड सर्विस एक ही शेड्यूल्ड जॉब को एक साथ 3 बार चलाएगी — अक्सर डुप्लीकेट ईमेल या साझा संसाधनों पर रेस कंडीशन का कारण बनता है।

ShedLock मानक समाधान है: यह एक साझा बाहरी स्टोर (डेटाबेस टेबल, Redis, या ZooKeeper) को डिस्ट्रिब्यूटेड लॉक के रूप में उपयोग करता है, और केवल वही इंस्टेंस टास्क चलाता है जो उस एक्ज़ीक्यूशन विंडो के लिए लॉक हासिल करने में सफल होता है।

@Scheduled(cron = "0 0 * * * *")
@SchedulerLock(name = "generateReport", lockAtMostFor = "10m", lockAtLeastFor = "1m")
public void generateReport() { ... }

Was this answer clear?