Originally posted by davidj6
So I leave the following snippet to other users trying to do automatic cache refresh
Code:
//refresh every 5 minutes
final int cacheTimeout = 300;
setCacheMaxAge (cacheTimeout);
final Timer t = new Timer () {
private int errorCount = 0;
@Override
public void run () {
try {
GWT.log ("Automatically fetching data for cache timeout");
refreshData ();
} catch (final Exception e) {
errorCount++;
if (errorCount > 3) {
SC.logWarn ("Disabling automatic refresh for datasource " + getID ()
+ ", since it just failed for 3 times");
cancel ();
}
}
}
/**
* Fetches fresh data for this DataSource AND notify related databound components to refresh
*/
private void refreshData () {
fetchData (null, new DSCallback () {
@Override
public void execute (final DSResponse response, final Object rawData, final DSRequest request) {
refreshCache (response, request);
}
});
}
/**
* Integrates the local cache with fresh data for this
* DataSource coming form the specified response
*
* @param response the response carrying fresh data
* @param request the original request
*/
private void refreshCache (final DSResponse response, final DSRequest request) {
GWT.log ("Data automatically fetched for cache timeout");
//a fake response to carry "commands"
final DSResponse carrier = new DSResponse ();
//request invalidation for all previously cached data
carrier.setInvalidateCache (true);
//copy the fresh data to the "fake" response
carrier.setData (response.getData ());
request.setOperationType (DSOperationType.UPDATE); // API not very clear
// integrates local cache with data passed with carrier AND notify related databound components to refresh
updateCaches (carrier, request);
}
};
t.scheduleRepeating (cacheTimeout * 1000);
Hope the snippet could be useful to someone else.
Many thanks to Isomorphic and davidj6.
Cheers
Davide
PS: I suggest that you integrate the updateCaches() JavaDoc and possibily the FAQ/best practices to inform users about the availability of these tricks (I mean - for instance - the combination of seInvalidateCache and UPDATE operation with fresh data)
Leave a comment: