user2009020
user2009020

Reputation: 287

Android - only calling a method every 15 minutes max, and using saved data otherwise

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

Answers (1)

Elliott Frisch
Elliott Frisch

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

Related Questions