Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2023-07-26
Problem Statement
Design and implement a lightweight Cron Job Scheduler that can schedule and execute tasks periodically based on user-defined time intervals or cron expressions (like "*/5 * * * *").
The system should allow tasks to be added, removed, and executed at the correct times — similar to how a UNIX cron service operates.
📋 Problem Description
You are required to design a Cron Job Scheduling system that allows:
•Users to register tasks (e.g., sending emails, cleaning logs, or generating reports).
•Each task to be executed automatically based on its schedule.
•The system to handle multiple jobs concurrently and reliably.
This exercise focuses on object-oriented design and threading/timing control rather than large-scale distributed scheduling.
🧱 Core Components to Design
1.Job (Interface / Abstract Class)
•Represents a unit of work to be executed.
•Has a method like execute().
2.CronExpression or Schedule
•Represents the schedule at which the job should run (could be time interval–based or cron-like).
•Provides method shouldRun(currentTime) to determine if a job is due.
3.CronJob
•Holds a Job instance and its Schedule.
•Tracks next execution time.
4.JobScheduler / CronScheduler
•Manages registration and removal of jobs.
•Periodically checks which jobs are due and triggers them.
•Can run jobs concurrently using threads or async tasks.
5.JobExecutor (optional)
•Executes jobs in separate threads or processes.
•Handles retries and error logging.
⚙️ Functional Requirements
1.Add/Remove Jobs
•addJob(jobName, job, schedule) → registers a job with its execution schedule.
•removeJob(jobName) → removes a registered job.
2.Job Execution
•The scheduler periodically checks the current time.
•If a job’s schedule matches the current time, it executes the job.
•Supports long-running or concurrent jobs.
3.Error Handling
•Handle job failures gracefully with retry or logging.
•Skip future executions if the system clock drifts or fails temporarily.
4.Job Status
•Maintain metadata such as last run time, next run time, and execution status (SUCCESS/FAILED).
🧩 Example Scenario
12# Define a simple job
3classEmailJob(Job):4 def execute(self):5print("Sending daily report email...")67# Create a scheduler
8scheduler =CronScheduler()9scheduler.addJob("daily_email",EmailJob(),"0 9 * * *") # Run every day at 9 AM
10scheduler.start()