Async & Messaging

Task Scheduler

Priority Queue Aur Worker Pool
💡 Task scheduler EK MANAGER hai jiske paas kaamon ki list hai aur kuch employees. Uska kaam hai sabse zaroori kaam pehle karana, aur ye dekhna ki koi employee do jagah na laga diya jaaye.

Core data structure PriorityQueue hai — tasks execution time ya priority se sorted. Worker threads queue se task uthaate hain. DelayQueue Java mein isi ke liye bana hai: task tabhi bahar aata hai jab uska time aa jaaye, tab tak worker thread block rehta hai (busy-wait nahi).

Recurring tasks (cron jaise) support karo — execute hone ke baad next run time calculate karke wapas queue mein daal do. Distributed setup mein sabse important sawaal: do servers ek hi task na uthaayein. Jawab hai distributed lock (Redis/Zookeeper) ya DB par atomic claim.

class Task implements Delayed {
  private final Instant scheduledAt;
  private final int priority;
  private final Runnable action;

  public long getDelay(TimeUnit unit) {
    return unit.convert(Duration.between(Instant.now(), scheduledAt));
  }
}

class Scheduler {
  private final DelayQueue<Task> queue = new DelayQueue<>();
  private final ExecutorService workers = Executors.newFixedThreadPool(N);

  void start() {
    while (running) {
      Task t = queue.take();          // time aane tak block
      workers.submit(() -> {
        t.run();
        if (t.isRecurring()) queue.put(t.nextOccurrence());
      });
    }
  }
}
Task scheduler EK MANAGER hai jiske paas kaamon ki list hai aur kuch employees. Uska kaam hai sabse zaroori kaam pehle karana, aur ye dekhna ki koi employee do jagah na laga diya jaaye.
1 / 2
⚡ Quick Recap
  • DelayQueue/PriorityQueue + worker thread pool = core design
  • Recurring task execute hone ke baad next occurrence queue mein wapas
  • Distributed mein atomic claim/lock — warna task do baar chalega
Is page mein (2 subtopics)

Recurring task ke liye cron expression parse karke NEXT execution time nikaalna padta hai. Interview mein poora cron parser likhne ki zaroorat nahi — bolo ki library use karoge, par CONCEPT batao: current time se aage ka pehla matching instant dhoondo.

Ek important detail: next run ka calculation SCHEDULED time se hona chahiye, ACTUAL execution time se nahi. Warna har run mein thodi thodi der jodkar drift ho jaata hai.

// ✅ Drift-free — scheduled time se agla nikaalo
Instant next = cronExpression.nextAfter(task.getScheduledAt());

// ❌ Drift aayega — execution der se hua to agla bhi der se
Instant next = cronExpression.nextAfter(Instant.now());

Task fail ho to kya karna hai — retry karo, skip karo, ya alert bhejo? Ye per-task configuration honi chahiye, global rule nahi.

Server down tha aur 3 runs miss ho gaye to kya karoge — sab catch-up chalao, sirf aakhri chalao, ya skip karo? Report generation ke liye sab chahiye, health check ke liye sirf latest. Ye poochna requirement clarity dikhata hai.

💡Tip: Long-running task ka case bolo — agla scheduled run aa gaya par pichla abhi chal raha hai. Overlap allow karna hai ya skip? Bina iske scheduler slowly saare threads kha jaata hai.