import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class TaskScheduler {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); // Single thread for simplicity
/**
* Schedules a task to run with a specified delay and period.
*
* @param task The task to execute. Should be a Runnable.
* @param initialDelay The delay in seconds before the first execution.
* @param period The time in seconds between subsequent executions.
*/
public void scheduleTask(Runnable task, long initialDelay, long period) {
scheduler.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);
}
/**
* Schedules a task to run after a specified delay, once.
*
* @param task The task to execute. Should be a Runnable.
* @param delay The delay in seconds before the task is executed.
*/
public void scheduleTaskOnce(Runnable task, long delay) {
scheduler.schedule(task, delay, TimeUnit.SECONDS);
}
/**
* Shuts down the scheduler gracefully.
*/
public void shutdown() {
scheduler.shutdown();
try {
if (!scheduler.awaitTermination(60, TimeUnit.SECONDS)) {
scheduler.shutdownNow();
}
} catch (InterruptedException e) {
scheduler.shutdownNow();
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
TaskScheduler scheduler = new TaskScheduler();
// Example task that might fail
Runnable myTask = () -> {
try {
//Simulate a potential error
if (Math.random() < 0.2) {
throw new RuntimeException("Simulated error!");
}
System.out.println("Task executed at: " + System.currentTimeMillis());
} catch (Exception e) {
System.err.println("Error executing task: " + e.getMessage()); // Simple error message
}
};
// Schedule a task to run every 5 seconds, starting after 2 seconds
scheduler.scheduleTask(myTask, 2, 5);
// Schedule a task to run once after 10 seconds
scheduler.scheduleTaskOnce(() -> System.out.println("One time task executed"), 10);
Thread.sleep(30000); // Run for 30 seconds
scheduler.shutdown();
System.out.println("Scheduler shutdown.");
}
}
Add your comment