问题陈述:我有一个包含计时器的类。
class DeleteTimer {
private Timer timer = new Timer();
private static Timer timerStatic;
public DeleteTimer(Member uid, String serverFilePath, String deleteTime) {
}
public static void start() {
timerStatic.schedule(new TimerTask() {
public void run() {
deleteFolder();
try {
timerStatic.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
private void deleteFolder() {
//delete a folder
return true;
}
}, 10000);
}
}
我有一个创建一些文件夹的程序,我希望这些文件夹在一段时间后自动删除。文件夹的名称不是固定的,因此每次我调用这个类时,我都会为它创建一个新对象。
DeleteTimer obj = new DeleteTimer();
obj.start();
这在第一次尝试时工作正常,但在我尝试使用新对象运行它时出现 java.lang.IllegalStateException: Timer already cancelled
。请帮忙。
最佳答案
timerStatic
被声明为 static
,这意味着 DeleteTimer
的所有实例共享相同的 timerStatic
实例。
如果您在 start
方法和 timerStatic
上删除 static
修饰符,这将阻止您的类的不同实例相互干扰.
关于java.lang.IllegalStateException : Timer already cancelled even when i am creating a new instance of the class itself 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7176096/