import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class QueryStringWatcher {
private static final int DEFAULT_RETRY_INTERVAL = 2; // seconds
private final int retryInterval;
private final Map<String, String> lastQueryString;
public QueryStringWatcher(int retryInterval) {
this.retryInterval = retryInterval;
this.lastQueryString = new HashMap<>();
}
public void watchQueryString(String queryString) {
// Store the current query string
lastQueryString.put(queryString);
// Simulate a background task that checks for changes
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(() -> {
String currentQueryString = getQueryString();
if (!currentQueryString.equals(lastQueryString.get(queryString))) {
System.out.println("Query string changed: " + currentQueryString);
lastQueryString.put(queryString, currentQueryString);
}
}, 0, retryInterval, TimeUnit.SECONDS);
}
private String getQueryString() {
// Placeholder for getting the query string. Replace with your actual implementation.
// This simulates reading from a request object or environment variable.
// Example: Read from System.getProperty("query.string")
String queryString = System.getProperty("query.string");
if (queryString == null) {
queryString = "default"; //Default value if not found
}
return queryString;
}
public static void main(String[] args) throws InterruptedException {
// Example Usage
QueryStringWatcher watcher = new QueryStringWatcher(5); // Retry every 5 seconds
// Simulate changes to the query string
String initialQueryString = "initial=value";
watcher.watchQueryString(initialQueryString);
Thread.sleep(2000); // Wait 2 seconds
watcher.watchQueryString("updated=value"); // Simulate a change
Thread.sleep(2000);
watcher.watchQueryString("updated2=value");
}
}
Add your comment