我有一个在类开始时加载的静态变量。我想每小时更新一次变量。问题是这样做的正确方法是什么?
我尝试这样做的方式如下,但它需要更新静态变量的方法在每个构造函数中:
import java.util.Date;
public class MyClass {
private static String globalString = "";
// initialize lastUpdate with two hours back to make sure first update happens
private static Date lastUpdate = new Date(System.currentTimeMillis() - (2 * (3600 * 1000)));
MyClass() {
updateGlobalString();
// DO MORE STUFF HERE...
}
MyClass(String string) {
updateGlobalString();
// DO MORE STUFF HERE...
}
private synchronized void updateGlobalString() {
// check if we need to update
if (lastUpdate.before(new Date(System.currentTimeMillis() - (3600 * 1000)))) {
// DO THINGS TO UPDATE globalString HERE...
lastUpdate = new Date();
}
}
}
还有其他想法/更好的方法吗?