Design a Task Scheduler, including main function and class structure, with working output.
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-11-26
Problem Statement
Design a Task Scheduler that allows scheduling, executing, and managing tasks at specified times or intervals. Focus is on OOP design, concurrency handling, and modularity, along with a working main function that demonstrates usage.
Functional Requirements
1.Task Scheduling
•Schedule a task to run once at a specific time.
•Schedule a task to run repeatedly at a fixed interval.
2.Task Management
•Cancel a scheduled task.
•Pause/resume a task (optional).
3.Execution
•Tasks should execute at the correct scheduled time.
•Support concurrent execution of multiple tasks.
4.Optional Features
•Task priority (high-priority tasks execute first if multiple are ready).
•Retry mechanism for failed tasks.
•Logging and metrics for executed tasks.
Non-Functional Requirements
•Concurrency: Multiple tasks may execute concurrently; ensure thread safety.
•Accuracy: Tasks should execute as close as possible to scheduled time.
•Extensibility: Easy to add new scheduling policies or task types.
Edge Cases & Constraints
•Task scheduled in the past → execute immediately or reject.
•Overlapping task executions → support concurrent execution or queue tasks.
•Long-running tasks → ensure they don’t block other scheduled tasks.
•Scheduler shutdown → handle graceful termination and optionally persist tasks.
Design Hints
•Key Classes / Interfaces:
•Task → represents a unit of work, stores execution time, interval, and task function.
•Scheduler → main class managing all tasks, adding, canceling, and executing tasks.
•WorkerThread → executes tasks concurrently.
•TaskQueue → priority queue or min-heap based on next execution time.
•Data Structures:
•PriorityQueue/Min-Heap → order tasks by next execution time.
•Map<TaskID, Task> → quick lookup for cancel/pause/resume.
•ThreadPool / Worker Threads → execute tasks concurrently.
•Design Patterns:
•Observer Pattern → optional, notify listeners when tasks start/complete.
•Strategy Pattern → optional, different scheduling policies.
•Command Pattern → encapsulate tasks as command objects.
Example Flow
1.Scheduler initialized → starts worker threads.
2.Task1 scheduled to run at t0 + 5s.
3.Task2 scheduled to run every 10 seconds.
4.Scheduler picks the next task from priority queue → assigns to a worker thread.
5.Task executes → completion logged.
6.If periodic → next execution time updated and re-inserted into queue.
Example Main Function
1
2import time
3from threading import Thread, Lock
4from queue import PriorityQueue
5
6class Task:
7 def __init__(self, name, func, run_at, interval=None):
8 self.name = name
9 self.func = func
10 self.run_at = run_at
11 self.interval = interval
12 def __lt__(self, other):
13 return self.run_at < other.run_at
14
15class Scheduler:
16 def __init__(self):
17 self.task_queue = PriorityQueue()
18 self.lock = Lock()
19 self.running = True
20 Thread(target=self.run).start()
21
22 def schedule(self, task):
23 with self.lock:
24 self.task_queue.put(task)
25
26 def run(self):
27 while self.running:
28 if not self.task_queue.empty():
29 task = self.task_queue.queue[0]
30 now = time.time()
31 if task.run_at <= now:
32 task = self.task_queue.get()
33 Thread(target=task.func).start()
34 if task.interval:
35 task.run_at += task.interval
36 self.schedule(task)
37 time.sleep(0.1)
38
39# Example usage
40def hello_task():
41 print("Hello, Task executed at", time.time())
42
43scheduler = Scheduler()
44scheduler.schedule(Task("Task1", hello_task, time.time() + 2))
45scheduler.schedule(Task("Task2", hello_task, time.time() + 5, interval=3))
46
47time.sleep(15) # Let tasks runEvaluation Areas
•Correct task scheduling and execution.
•Thread-safe priority queue management.
•Support for recurring tasks.
•Extensible OOP design for new features.
This LLD problem tests OOP design, concurrency handling, scheduling logic, and working implementation of a core system component