import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class LogReloader {
private final Runnable reloadTask;
private final long reloadIntervalMillis;
private ScheduledExecutorService scheduler;
private boolean running = false;
public LogReloader(Runnable reloadTask, long reloadIntervalMillis) {
this.reloadTask = reloadTask;
this.reloadIntervalMillis = reloadIntervalMillis;
this.scheduler = Executors.newSingleThreadScheduledExecutor();
}
public void start() {
if (!running) {
scheduler.scheduleAtFixedRate(reloadTask, 0, reloadIntervalMillis, TimeUnit.MILLISECONDS);
running = true;
}
}
public void stop() {
if (running) {
scheduler.shutdown();
running = false;
}
}
public static void main(String[] args) {
// Example Usage
LogReloader reloader = new LogReloader(() -> {
// Simulate reloading log entries
System.out.println("Reloading log entries...");
try {
Thread.sleep(1000); // Simulate some work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Log entries reloaded.");
}, 5000); // Reload every 5 seconds
reloader.start();
try {
Thread.sleep(20000); // Run for 20 seconds
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
reloader.stop();
System.out.println("Log reloader stopped.");
}
}
Add your comment