Cron Job to execute a task

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

1 2# Define a simple job 3class EmailJob(Job): 4 def execute(self): 5 print("Sending daily report email...") 6 7# Create a scheduler 8scheduler = CronScheduler() 9scheduler.addJob("daily_email", EmailJob(), "0 9 * * *") # Run every day at 9 AM 10scheduler.start()


Output:

1 2[09:00:00] Executing job: daily_email 3Sending daily report email... 4[09:00:02] Job completed successfully.


⚙️ Non-Functional Requirements


Aspect and Requirement


Scalability

Should handle dozens of jobs with different schedules.



Reliability

Must ensure scheduled jobs run even after restarts (extendable).


Accuracy

Time-based triggering within ±1 second margin.



Concurrency

Support multiple jobs executing simultaneously.


Extensibility

Easy to plug in new job types (email, cleanup, etc.).



🧠 Design Discussion Points


•How would you store jobs persistently (e.g., in DB or file)?
•How to support distributed scheduling (clustered setup)?
•How can you parse and validate cron expressions efficiently?
•What happens if a job takes longer than its schedule interval?
•How would you ensure thread safety in the scheduler?


✅ Deliverables


•UML class diagram for Job, CronScheduler, and CronJob.
•Example implementation (Python/Java).
•Logs showing job execution, scheduling, and error handling.


🚀 Stretch Goals


•Implement retry logic with exponential backoff.
•Support job persistence using files or databases.
•Add web dashboard for managing scheduled jobs.
•Integrate metrics and alerts for job failures or delays.


Solution

Comments