1. import java.util.concurrent.Executors;
  2. import java.util.concurrent.ScheduledExecutorService;
  3. import java.util.concurrent.TimeUnit;
  4. public class LogReloader {
  5. private final Runnable reloadTask;
  6. private final long reloadIntervalMillis;
  7. private ScheduledExecutorService scheduler;
  8. private boolean running = false;
  9. public LogReloader(Runnable reloadTask, long reloadIntervalMillis) {
  10. this.reloadTask = reloadTask;
  11. this.reloadIntervalMillis = reloadIntervalMillis;
  12. this.scheduler = Executors.newSingleThreadScheduledExecutor();
  13. }
  14. public void start() {
  15. if (!running) {
  16. scheduler.scheduleAtFixedRate(reloadTask, 0, reloadIntervalMillis, TimeUnit.MILLISECONDS);
  17. running = true;
  18. }
  19. }
  20. public void stop() {
  21. if (running) {
  22. scheduler.shutdown();
  23. running = false;
  24. }
  25. }
  26. public static void main(String[] args) {
  27. // Example Usage
  28. LogReloader reloader = new LogReloader(() -> {
  29. // Simulate reloading log entries
  30. System.out.println("Reloading log entries...");
  31. try {
  32. Thread.sleep(1000); // Simulate some work
  33. } catch (InterruptedException e) {
  34. Thread.currentThread().interrupt();
  35. }
  36. System.out.println("Log entries reloaded.");
  37. }, 5000); // Reload every 5 seconds
  38. reloader.start();
  39. try {
  40. Thread.sleep(20000); // Run for 20 seconds
  41. } catch (InterruptedException e) {
  42. Thread.currentThread().interrupt();
  43. }
  44. reloader.stop();
  45. System.out.println("Log reloader stopped.");
  46. }
  47. }

Add your comment