Reputation: 287
I'm writing an app with a method that will be accessing data online. However, we are maximally allowed to query the website at most once every 15 minutes. If the 15 minutes has not elapsed, I want to use the data from the most recent query. What are the best practices for checking the last time a method was called?
Upvotes: 0
Views: 89
Reputation: 201497
Just use a cache with a 20 minute expiration and you should be good to go. I would prefer an existing one to implementing my own, but for one field it's trivial - get the time when you retrieve the resource and add 20 minutes. If the current time is after you can get it again,
Date cachedAt = null;
String cachedContent = null;
String getCachedThing() {
if (cachedContent != null && cachedAt != null &&
new Date().before(cachedAt)) {
return cachedContent;
}
getThing();
return cachedContent;
}
private void getThing() {
// get resource.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 20);
cachedAt = cal.getTime();
cachedContent = "myWebPage";
}
Upvotes: 1