1. import java.util.concurrent.ExecutorService;
  2. import java.util.concurrent.Executors;
  3. import java.util.concurrent.ScheduledExecutorService;
  4. import java.util.concurrent.TimeUnit;
  5. public class TaskScheduler {
  6. private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); // Single thread for simplicity
  7. /**
  8. * Schedules a task to run with a specified delay and period.
  9. *
  10. * @param task The task to execute. Should be a Runnable.
  11. * @param initialDelay The delay in seconds before the first execution.
  12. * @param period The time in seconds between subsequent executions.
  13. */
  14. public void scheduleTask(Runnable task, long initialDelay, long period) {
  15. scheduler.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);
  16. }
  17. /**
  18. * Schedules a task to run after a specified delay, once.
  19. *
  20. * @param task The task to execute. Should be a Runnable.
  21. * @param delay The delay in seconds before the task is executed.
  22. */
  23. public void scheduleTaskOnce(Runnable task, long delay) {
  24. scheduler.schedule(task, delay, TimeUnit.SECONDS);
  25. }
  26. /**
  27. * Shuts down the scheduler gracefully.
  28. */
  29. public void shutdown() {
  30. scheduler.shutdown();
  31. try {
  32. if (!scheduler.awaitTermination(60, TimeUnit.SECONDS)) {
  33. scheduler.shutdownNow();
  34. }
  35. } catch (InterruptedException e) {
  36. scheduler.shutdownNow();
  37. Thread.currentThread().interrupt();
  38. }
  39. }
  40. public static void main(String[] args) throws InterruptedException {
  41. TaskScheduler scheduler = new TaskScheduler();
  42. // Example task that might fail
  43. Runnable myTask = () -> {
  44. try {
  45. //Simulate a potential error
  46. if (Math.random() < 0.2) {
  47. throw new RuntimeException("Simulated error!");
  48. }
  49. System.out.println("Task executed at: " + System.currentTimeMillis());
  50. } catch (Exception e) {
  51. System.err.println("Error executing task: " + e.getMessage()); // Simple error message
  52. }
  53. };
  54. // Schedule a task to run every 5 seconds, starting after 2 seconds
  55. scheduler.scheduleTask(myTask, 2, 5);
  56. // Schedule a task to run once after 10 seconds
  57. scheduler.scheduleTaskOnce(() -> System.out.println("One time task executed"), 10);
  58. Thread.sleep(30000); // Run for 30 seconds
  59. scheduler.shutdown();
  60. System.out.println("Scheduler shutdown.");
  61. }
  62. }

Add your comment