Overview
The Scheduler Design Pattern is used to manage the execution of tasks at specified times or intervals. This pattern is often implemented in systems that require periodic task execution, such as cron jobs or event-driven systems.
Key Characteristics
- Provides a mechanism to schedule tasks for one-time or repeated execution.
- Can prioritize or queue tasks based on requirements.
- Facilitates the efficient management of task execution without manual intervention.
Implementation
The following is an example of a Scheduler implementation in Java using the ScheduledExecutorService:
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
class Task implements Runnable {
private final String name;
public Task(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println("Executing task: " + name + " at " + System.currentTimeMillis());
}
}
public class SchedulerDemo {
public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
Task task1 = new Task("Task 1");
Task task2 = new Task("Task 2");
// Schedule task1 to run after an initial delay of 2 seconds, repeating every 5 seconds
scheduler.scheduleAtFixedRate(task1, 2, 5, TimeUnit.SECONDS);
// Schedule task2 to run once after a delay of 3 seconds
scheduler.schedule(task2, 3, TimeUnit.SECONDS);
// Schedule the scheduler to shut down after 20 seconds
scheduler.schedule(() -> {
System.out.println("Shutting down scheduler");
scheduler.shutdown();
}, 20, TimeUnit.SECONDS);
}
}
When to Use
- When tasks need to be executed periodically or at specific times.
- When you need to manage multiple concurrent tasks efficiently.
Advantages
- Automates task execution without manual intervention.
- Supports repeated execution of tasks with defined intervals.
- Facilitates efficient management of system resources.
Disadvantages
- Requires careful management of task dependencies and priorities.
- May lead to resource contention if too many tasks are scheduled concurrently.